C# 最短路径问题——Dijkstra(二叉堆优化)

Description

平面上有n个点(N<=100),每个点的坐标均在-10000~10000之间。其中的一些点之间有连线。若有连线,则表示可从一个点到达另一个点,即两点间有通路,通路的距离为两点直线的距离。现在的任务是找出从一点到另一点之间的最短路径。

Input

输入文件short.in,共有n+m+3行,其中:
第一行为一个整数n。
第2行到第n+1行(共n行),每行的两个整数x和y,描述一个点的坐标(以一个空格隔开)。
第n+2行为一个整数m,表示图中的连线个数。
此后的m行,每行描述一条连线,由两个整数I,j组成,表示第i个点和第j个点之间有连线。
最后一行:两个整数s和t,分别表示源点和目标点。

Output

输出文件short.out仅一行,一个实数(保留两位小数),表示从S到T的最短路径的长度。

Sample Input

5
0 0
2 0
2 2
0 2
3 1
5
1 2
1 3
1 4
2 5
3 5
1 5

Sample Output

3.41


使用Dijstra实现,利用二叉堆优化,时间复杂度为 nlogn(n个结点 * 堆化时间为logn)。
Con.Read()是我自己封装的控制台输入,可以看看这篇文章

算法分析:

Dijkstra需要准备这几样东西:

  • 起始结点
  • 记录当前未标记过的点的列表,可以用数组或者用堆实现
  • 记录当前最短路径的列表,即minDisList

Dijkstra思路是这样的:

  1. 每一次从未标记列表拿一个离起始点距离最小的出来,作为当前结点

如果未标记列表使用数组实现那么取最小值需要n的时间复杂度,使用二叉堆只需要1的复杂度,最后删除二叉堆最小值后需要堆化,复杂度为logn,当然更甚可以用斐波那契堆实现

  1. 将开始顶点到该结点的所有相邻结点的距离更新到minDisList(比minDisList记录的小才更新)
  2. 重复1-2,直到未标记列表为空

Dijkstra为什么能找到最短距离:

因为每次循环都找的是距离起始点的最短距离的结点

定义结点

    public class Vector2:IComparable<Vector2>
    {
        public int x;
        public int y;
        public int index;
        public double distance = double.MaxValue;//到当前结点的最短距离
        public Vector2(int x, int y, int index) => (this.x, this.y, this.index) = (x, y, index);
        public static double Dis(Vector2 point1, Vector2 point2) => Math.Sqrt(Math.Pow(point1.x - point2.x, 2) + Math.Pow(point1.y - point2.y, 2));

        public int CompareTo(Vector2 other)
        {
            if(other.distance < distance)
                return 1;
            else if (other.distance == distance)
                return 0;
            return -1;
        }

        public override string ToString() => $"[{x},{y}]";
    }

Dijkstra

    public class Dijkstra
    {
        double[] minDisList;
        MinHeap<Vector2> unmarkHeap;
        Dictionary<int, Vector2> Index2PointMapping; //结点序号到结点的映射
        Dictionary<int, List<int>> Point2PointMapping;//某结点到某节点的映射 1-n
        int startIndex;
        int num;

        //初始化数据
        public Dijkstra( int num, int startIndex, Dictionary<int, Vector2> index2PointMapping, Dictionary<int, List<int>> point2PointMapping)
        {
            Index2PointMapping = index2PointMapping;
            Point2PointMapping = point2PointMapping;
            this.startIndex = startIndex;
            this.num = num;

            index2PointMapping[startIndex].distance = 0;
            minDisList = new double[num + 1];

            //初始化起点的邻接结点距离
            foreach (var index in Point2PointMapping[startIndex])
            {
                index2PointMapping[index].distance = minDisList[index];
            }
            //让最小距离都为最大
            for (int i = 0; i < minDisList.Length; i++)
            {
                minDisList[i] = double.MaxValue;
            }
            //起点距离为0
            minDisList[startIndex] = 0;
			
			//初始化堆
            var array = Index2PointMapping.Values.ToArray();
            unmarkHeap = new MinHeap<Vector2>(array,num);
        }
        
        //找与index相邻的最短路径
        public bool FindMinPath(int index, Action<int, double> index_tempDisCallback)
        {
            //没有出度时说明没找到
            if (!Point2PointMapping.ContainsKey(index))
                return false;    
            
            var nextChioceList = Point2PointMapping[index];
            
            //寻找当前结点的最短路径
            foreach (var item in nextChioceList)
            {
                var tempDis = Vector2.Dis(Index2PointMapping[index], Index2PointMapping[item]);
                index_tempDisCallback(item, tempDis);
            }
            return true;
        }
        //生成Dijstra图
        public double[] GenerateMap()
        {
            Vector2 currentPoint = Index2PointMapping[startIndex];
            //算法开始
            while (unmarkHeap.Count > 0)
            {
                //从未被标记的点里拿一个最小的出来,这里是堆顶
                currentPoint = unmarkHeap.GetMin();
                Console.WriteLine($"移除:{currentPoint.index}");

                //修正并更新minDisList
                FindMinPath(currentPoint.index, (index, tempDis) =>
                 {
                     var dis = currentPoint.distance + tempDis;
                     if(dis < minDisList[index])
                     {
                        minDisList[index] = dis;
                        Index2PointMapping[index].distance = dis;                          
                     }
                 });
                 
                 //移除最小结点并堆化
                 unmarkHeap.TryRemoveMin();
                 
            }
            //ToFormatString是我自己封装的拓展方法,不用管这个
            Console.WriteLine("生成Dijkstra图:" + minDisList[1..minDisList.Length].ToFormatString<double>());
            return minDisList[1..minDisList.Length];
        }
    }

测试

    //测试
    public class MainTest
    {
	    public static void Main(string[] args)
	    {
	        //输入所有点
	        Con.Read(out int n);
	        Dictionary<int, Vector2> Index2PointMapping = new();
	        for (var i = 0; i < n; i++)
	        {
	            Con.Read(out int x, out int y);
	            Vector2 point = new(x, y, i + 1);
	            Index2PointMapping.Add(i + 1, point);
	        }
	
	        //输入连线
	        Con.Read(out int m);
	        Dictionary<int, List<int>> Point2PointMapping = new();
	        for (var i = 0; i < m; i++)
	        {
	            Con.Read(out int x, out int y);
	            if (Point2PointMapping.TryGetValue(x, out List<int> list))
	            {
	                list.Add(y);
	            }
	            else
	                Point2PointMapping.Add(x, new List<int>() { y });
	        }
	        //输入起始点和终点
	        Con.Read(out int start, out int end);
	
	        var dijkstra = new Dijkstra(n,start, Index2PointMapping, Point2PointMapping);
	        var minDis = dijkstra.GenerateMap();
	        Console.WriteLine(Math.Round(minDis[end-1], 2));
        }
    }

结果输出

移除:1
移除:2
移除:4
移除:3
移除:5
生成Dijkstra图:[0, 2, 2.8284271247461903, 2, 3.414213562373095]
3.41
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
离字典,将起始节点的距离设为0,其他节点的距离设为无穷大 distances = {node: sys.maxsize for node in graph} distances[start] = 0 # 初始化已访问节点的集合和未访以下是使用问节点D的集ijkstra合 visited = set() unvisited算法解最短路径的Python = set(graph) while unvisited: # 代码示例: ```python class D选择当前ijkstra距: def __init__(self, graph离最小的节点 , start, current goal): self.graph = graph # 邻接表_node = min(unvisited, key=lambda self node: distances[node]) # 更新.start = start当前节点的 # 起邻居节点点 self.goal =的距离 goal # 终点 for neighbor in graph self.open[current_node]: _list = {} if neighbor in # open 表 self.closed_list unvisited: new_distance = distances[current_node] + = {} graph[current_node][neighbor # closed 表 self.open_list[start] if new_distance] = < distances[neighbor]: 0.0 # 将 distances[neighbor] = new_distance # 将当前起点放入 open_list 中 self.parent = {节点标记start:为已访 None} 问,并从未访问集合中移除 visited.add # 存储节点的父子关系。键为(current_node) 子节点, unvisited值为父.remove(current_node) return节点。方便做最 distances def print后_path(dist路径的ances,回 start溯 self.min, end): _dis = None # 根 # 最短路径的长度 def shortest_path据距离字典和终点节点(self): while True: ,逆向 if self打印路径.open_list is path = [end None: ] print('搜索 current_node =失败 end while current_node !=, 结束!') break distance start: , min_node = for neighbor in graph min(zip[current_node]: if(self.open_list distances[current.values(), self_node] ==.open_list.keys distances[neighbor())) #] + graph 取出距[neighbor][current_node]: 离最小的节点 self path.open_list.pop.append(min_node)(neighbor) current_node = neighbor break path.reverse() # 将其从 open_list 中去除 self print.closed("_list[minShortest_node] = path from", distance # 将节点加入 closed start, "to", end,_list ":", "->".join(path)) # 示例 中 if min_node == self.goal: # 如果节点为图的邻接矩阵终点 self.min_dis = distance 表示 graph shortest = { _path = [ 'Aself.goal]': {'B': # 5, 'C 记录从': 终1}, 点回溯的路径 'B

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值