The function Dijkstra is to find the shortest path from Vertex S to every other vertices in a given Graph. The distances are stored in dist[], and path[] records the paths. The MGraph is defined as the following: typedef struct GNode *PtrToGNode; struct GNode{ int Nv; /* Number of vertices */ int Ne; /* Number of edges */ WeightType G[MaxVertexNum][MaxVertexNum]; /* adjacency matrix */ }; typedef PtrToGNode MGraph; void Dijkstra( MGraph Graph, int dist[], int path[], Vertex S ) { int collected[MaxVertexNum]; Vertex V, W; for ( V=0; V<Graph->Nv; V++ ) { dist[V] = Graph->G[S][V]; path[V] = -1; collected[V] = false; } dist[S] = 0; collected[S] = true; while (1) { V = FindMinDist( Graph, dist, collected ); if ( V==ERROR ) break; collected[V] = true; for( W=0; W<Graph->Nv; W++ ) if ( collected[W]==false && Graph->G[V][W]<INFINITY ) { if ( ) { dist[W] = ; path[W] = ; } } } /* end while */ }
时间: 2024-04-27 07:25:16 浏览: 147
在Dijkstra函数中,缺少一个条件判断语句,用来判断当前节点W是否可以通过V到达S的距离更短。应该在if语句中加上这个条件判断,如下所示:
if ( collected[W]==false && Graph->G[V][W]<INFINITY ) {
if ( dist[V] + Graph->G[V][W] < dist[W] ) {
dist[W] = dist[V] + Graph->G[V][W];
path[W] = V;
}
}
这样就可以在更新dist[W]和path[W]的时候,同时判断是否需要更新最短路径。
相关问题
Use Dijkstra's algorithm to find the shortest paths from vertex a to other vertices. In which order that the results must be obtained?
The order of the results obtained from using Dijkstra's algorithm to find the shortest paths from vertex a to other vertices is not specified by the algorithm itself. However, typically the results are obtained in ascending order based on the distance from vertex a to each of the other vertices.
阅读全文