用C#编写Dijkstra算法,并输出最短路径

Dijkstra算法的基本思想是:每次找到离源点最近的一个顶点,然后以该顶点为中心进行扩展,最终得到源点到其余所有点的最短路径。具体基本步骤如下:

1.将所有的顶点分为两部分:已知最短路径的顶点集合P和未知最短路径的顶点集合Q。最开始,已知最短路径的顶点集合P中只有一个源点一个顶点。我们这里用一个book数组来记录哪些店在集合P中。例如对于某个顶点i,如果book[i]为1则表示这个顶点在集合P中,如果book[I]为0则表示这个顶点在集合Q中。

2.设置源点s到自己的最短路径为0即dis[s]=0。若存在有源点能直接到达的顶点i,则把这个dis[i]设为dis[s,i]。同时把所有其他(源点不能直接到达的)顶点的最短路径设为无限大inf=100000000。

3.在集合Q的所有顶点中选择一个离源点最近的顶点u(即dis[u]最小)加入到集合P。并考察所有以点u为起点的边,对每一条边进行松弛操作。例如存在一条从u到v的边,那么可以通过将边u=>v添加到尾部来拓展一条从s到v的路径,这条路径的长度是dis[u]+e[u][v]。如果这个值比目前已知的dis[v]的值要小,我们可以用新值来替代当前dis[v]中的值。

4.重复第三步,如果集合Q为空,算法结束。最终dis数组中的值就是源点到所有顶点的最短路径。

C#代码:(路径存在list path中)

 class Program
    {
        public static List<int> path = new List<int>();//存储路径
        public static int n = 6;
        public static int inf = 100000000;//无路段--------
        public static int[,] cost = new int[n, n];
        public static int[] f;
        public static int[] t;
        public static double[] c;

        static void Main(string[] args)
        {
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if (i != j)
                    {
                        cost[i, j] = inf;
                    }
                    else
                    {
                        cost[i, j] = 0;
                    }
                }
            }
            ReadNode1(@"cost.txt");

            ShortestPath();
            //ShortestPath1();
            //BellmanFord();
            Console.ReadKey();
        }

        static void ReadNode1(string DataPath)//读取邻接表(如:1	2	1 )结点1到结点2距离为1:
        {



            if (!File.Exists(DataPath))
            {
                Console.WriteLine("{0} does not exist!", DataPath);
                return;
            }

            StreamReader sr = File.OpenText(DataPath);
            String input;
            String[] Data = null;
            int index = 0;
            while ((input = sr.ReadLine()) != null)
            {
                if (input == "") continue;
                Data = input.Split('\t');
                cost[int.Parse(Data[0]) - 1, int.Parse(Data[1]) - 1] = int.Parse(Data[2]);
                index++;

            }
            sr.Close();
        }
        static void ShortestPath()
        {
            int g = 1;//出发点
            int h = 4;//终点

            int[] book = new int[n]; //book[i]=0表示此结点最短路未确定,为1表示已确定
                                     //double[,] cost = Matrix.LoadData("cost1.txt", '\t');//路之间的权值,即距离

            double[] distance = new double[n];//出发点到各点最短距离
            int[] last1 = new int[n];//存储最短路径,每个结点的上一个结点
            double min;
            int u = 0;

            //初始化distance,这是出发点到各点的初始距离
            for (int i = 0; i < n; i++)
            {
                //distance[i] = cost[0, i];
                distance[i] = cost[g, i];
            }

            //初始化出发点的book
            for (int i = 0; i < n; i++)
            {

                last1[i] = g;
            }

            last1[g] = -1;
            book[g] = 1;

            //核心算法
            for (int i = 0; i < n - 1; i++)
            {
                min = inf;

                //找到离g号结点最近的点
                for (int j = 0; j < n; j++)
                {
                    if (book[j] == 0 && distance[j] < min && distance[j] != 0)
                    {
                        min = distance[j];
                        u = j;
                    }
                }
                book[u] = 1;

                for (int v = 0; v < n; v++)
                {
                    if (cost[u, v] < inf && cost[u, v] != 0)
                    {
                        if (distance[v] > distance[u] + cost[u, v])
                        {
                            distance[v] = distance[u] + cost[u, v];
                            last1[v] = u;
                        }

                    }
                }
            }
            Console.WriteLine("{0}点到各节点最短距离:", g);
            for (int i = 0; i < n; i++)
            {
                if (distance[i] < inf)
                {
                    Console.Write("{0} ", distance[i]);
                }
                else
                {
                    Console.Write("无法到达");
                }

            }

            Console.WriteLine();

            int k = h;
            path.Add(k);

            while (k != g)
            {
                if (distance[k] >= inf)
                {
                    Console.WriteLine("无法到达该节点");
                    break;
                }
                k = last1[k];

                path.Add(k);
            }
            path.Reverse();
            Console.WriteLine("到终点最短路径");
            foreach (int i in path)
            {
                Console.Write(i + 1 + " ");
            }
            Console.WriteLine();
            Console.WriteLine();

        }

 

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你好!下面是使用C#实现Dijkstra算法输出最短路径的示例代码: ```c# using System; using System.Collections.Generic; public class DijkstraAlgorithm { private int numVertices; private List<List<Node>> adjacencyList; private class Node { public int Vertex { get; } public int Weight { get; } public Node(int vertex, int weight) { Vertex = vertex; Weight = weight; } } public DijkstraAlgorithm(int numVertices) { this.numVertices = numVertices; adjacencyList = new List<List<Node>>(numVertices); for (int i = 0; i < numVertices; i++) { adjacencyList.Add(new List<Node>()); } } public void AddEdge(int source, int destination, int weight) { adjacencyList[source].Add(new Node(destination, weight)); } public void ShortestPath(int source) { int[] distances = new int[numVertices]; bool[] visited = new bool[numVertices]; for (int i = 0; i < numVertices; i++) { distances[i] = int.MaxValue; visited[i] = false; } distances[source] = 0; for (int i = 0; i < numVertices - 1; i++) { int minDistanceVertex = MinimumDistance(distances, visited); visited[minDistanceVertex] = true; foreach (Node node in adjacencyList[minDistanceVertex]) { if (!visited[node.Vertex] && distances[minDistanceVertex] != int.MaxValue && distances[minDistanceVertex] + node.Weight < distances[node.Vertex]) { distances[node.Vertex] = distances[minDistanceVertex] + node.Weight; } } } PrintShortestPaths(distances, source); } private int MinimumDistance(int[] distances, bool[] visited) { int min = int.MaxValue; int minIndex = -1; for (int i = 0; i < numVertices; i++) { if (!visited[i] && distances[i] <= min) { min = distances[i]; minIndex = i; } } return minIndex; } private void PrintShortestPaths(int[] distances, int source) { Console.WriteLine("Vertex\tDistance from Source"); for (int i = 0; i < numVertices; i++) { Console.WriteLine("{0}\t\t{1}", i, distances[i]); } } public static void Main(string[] args) { DijkstraAlgorithm graph = new DijkstraAlgorithm(6); graph.AddEdge(0, 1, 4); graph.AddEdge(0, 2, 1); graph.AddEdge(1, 3, 1); graph.AddEdge(2, 1, 2); graph.AddEdge(2, 3, 5); graph.AddEdge(3, 4, 3); graph.AddEdge(4, 1, 3); graph.AddEdge(4, 0, 2); int source = 0; graph.ShortestPath(source); } } ``` 这是一个简单的示例,你可以根据自己的需求进行修改。在示例代码中,我们首先定义了一个 `DijkstraAlgorithm` 类来实现Dijkstra算法。然后,我们可以使用 `AddEdge` 方法添加图的边。最后,在 `Main` 方法中,我们创建了一个具有6个顶点的图,并计算从指定源点到其他各个顶点的最短路径。 希望能帮到你!如果你还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值