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.
上述算法已在 Wikipedia 中提到了 Dijkstra 最短路径。我在这里无法理解的是,虽然我们将所有顶点的距离设置为无穷大[第 3 行],但在第 9 行我们正在分配u := vertex in Q with smallest dist[]
,但由于所有距离都是无限的(如第 3 行中设置的那样)怎么可能有最小的距离?