1. 程式人生 > >單源最短路徑Dijkstra演算法

單源最短路徑Dijkstra演算法

1.單源最短路徑

函式:返回還未被收錄頂點中dist最小者

 1 Vertex FindMinDist(MGraph Graph, int dist[], int collected[])
 2 {
 3     /*返回未被收錄頂點中dist最小者*/
 4     Vertex MinV, V;
 5     int MinDist = INFINITY;
 6 
 7 
 8     for (V = 0; V < Graph->Nv; ++V)
 9     {
10         if (collected[V] == false && dist[V] < MinDist)
11 { 12 MinDist = dist[V]; 13 MinV = V; //更新對應頂點 14 } 15 } 16 if (MinDist < INFINITY) //若找到最小值 17 return MinV; 18 else 19 return -1; 20 }
單源最短路徑Dijkstra演算法
 1 /*單源最短路徑Dijkstra演算法*/
 2 /*dist陣列儲存起點到這個頂點的最小路徑長度
*/ 3 bool Dijkstra(MGraph Graph, int dist[], int path[], Vertex S) 4 { 5 int collected[MaxVertexNum]; 6 Vertex V, W; 7 8 /*初始化,此處預設鄰接矩陣中不存在的邊用INFINITY表示*/ 9 for (V = 0; V < Graph->Nv; V++) 10 { 11 dist[V] = Graph->G[S][V]; //用S頂點對應的行向量分別初始化dist陣列 12 if
(dist[V] < INFINITY) //如果(S, V)這條邊存在 13 path[V] = S; //將V頂點的父節點初始化為S 14 else 15 path[V] = -1; //否則初始化為-1 16 collected[V] = false; //false表示這個頂點還未被收入集合 17 } 18 19 20 /*現將起點S收錄集合*/ 21 dist[S] = 0; //S到S的路徑長度為0 22 collected[S] = true; 23 24 while (1) 25 { 26 V = FindMinDist(Graph, dist, collected); //V=未被收錄頂點中dist最小者 27 if (V == -1) //如果這樣的V不存在 28 break; 29 collected[V] = true; //將V收錄進集合 30 for (W = 0; W < Graph->Nv; W++) //對V的每個鄰接點 31 { 32 /*如果W是V的鄰接點且未被收錄*/ 33 if (collected[W] == false && Graph->G[V][W] < INFINITY) 34 { 35 if (Graph->G[V][W] < 0) //若有負邊,不能正常解決,返回錯誤標記 36 return false ; 37 if (dist[W] > dist[V] + Graph->G[V][W]) 38 { 39 dist[W] = dist[V] + Graph->G[V][W]; //更新dist[W] 40 path[W] = V; //更新S到W的路徑 41 } 42 } 43 } 44 } 45 return true; 46 }