【发布时间】:2011-02-09 06:44:54
【问题描述】:
function Dijkstra(Graph, source):
for each vertex v in Graph: // Initializations
dist[v] := infinity ; // Unknown distance function from source to v
previous[v] := undefined ; // Previous node in optimal path from source
end for ;
dist[source] := 0 ; // Distance from source to source
Q := the set of all nodes in Graph ;
// All nodes in the graph are unoptimized - thus are in Q
while Q is not empty: // The main loop
u := vertex in Q with smallest dist[] ;
if dist[u] = infinity:
break ; // all remaining vertices are inaccessible from source
fi ;
remove u from Q ;
for each neighbor v of u: // where v has not yet been removed from Q.
alt := dist[u] + dist_between(u, v) ;
if alt < dist[v]: // Relax (u,v,a)
dist[v] := alt ;
previous[v] := u ;
fi ;
end for ;
end while ;
return dist[] ;
end Dijkstra.
上面的算法已经在维基百科中提到了 Dijkstra 最短路径。我在这里无法理解的是,虽然我们将所有顶点的距离设置为无穷大 [第 3 行],但在第 9 行,我们分配了u := vertex in Q with smallest dist[],但由于所有距离都是无限的(如在行中设置数字 3) 怎么会有最小的距离?
【问题讨论】:
-
知道了,认为 dist_between(u, v) 也在计算基于 dist[] 的距离