【C# dijkstra迪杰斯特拉算法 最短路径】迪杰斯特拉算法 最短路径的C#实现

 

作者:cuihao0532

转载请注明出处:http://www.cnblogs.com/cuish/archive/2013/06/09/3129106.html

适用于有向图和无向图,邻接矩阵存储方式

 

 1 //graph:邻接矩阵形式存储的有向图或无向图
 2 //nLength:点的个数
 3 //nStart:起点在邻接矩阵中的位置
 4 //nEnd:终点在邻接矩阵中的位置
 5 //INFINITY: 表示没有路径的最大值
 6 //返回值:保存最短路径正确顺序的int数组,数组中只有一个起点时说明没有路径
 7 //D[]数组保存起点到各个点的最短路径长度
 8 //需要注意的是:由于在代码有中min + graph[nEnd, w]这样的操作,因此最大值的选取要注意
 9 
10 
11 public static int[] dijkstra(int[,] graph,  int nLength,  int  nStart, int nEnd, INT INFINITY )
12 {
13     int t = nEnd;
14     int[] P = new int[nLength];
15     int[] D = net int [nLength];    
16     int[] final = new int[nLength];
17 
18     for(int i = 0; i < nLength; ++ i)
19     {
20         D[i] = graph[nStart, i];
21         P[i] = nStart;
22         final[i] = 0;
23     
24     } //for
25 
26     final[nStart] = 1;
27     
28     for(int i = 1;i < nLength; ++ i)
29     {
30         int min = INFINITY;  //最大值
31         for(int w = 0; w < nLength; ++ w)
32         {
33             if(final[w] == 0 && D[w] < min)
34             {
35                 nEnd = w;
36                 min = D[w];
37             }
38         } //for
39 
40         final[nEnd] = 1;
41 
42         for(int w = 0; w < nLength; ++ w)
43         {
44             if(final[w] == 0 && (min + graph[nEnd, w] < D[w]))
45             {
46                 D[w] = min + graph[nEnd, w];
47                 P[w] = nEnd;
48             }//if
49 
50         } //for 
51     
52     } //for
53 
54     string r = null;
55     if(D[t] < INFINITY)
56     {
57         r = t.ToString() + ",";  //最短路径上的第一个点为本身(后面要把这个顺序逆置)
58     }
59 
60     do
61     {
62         r += P[t].ToString() + ",";  //找所有的路径上的点;
63         t = P[t];
64     }while(t != nStart);
65 
66     char[] arr = r.ToCharArray();
67     Array.Reverse(arr);                      //逆置
68 
69     string strRet = new string(arr); //逆置后的string
70     
71     string[] str = strRet.Split(new char[] {','}); //按逗号分割
72     int [] nArrResult = new int[str.Length - 1]; //第一个为空,减少一个
73 
74     for(int count = 1; count < str.Length; ++ count)
75     {
76         nArrResult[count - 1] = int.Parse(str[count]);
77     }
78 
79     return nArrResult;
80 
81 
82 }

 

 

 

原文地址:https://www.cnblogs.com/cuish/p/3129106.html