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.
the above algorithm has been mentioned in Wikipedia for Dijkstra shortest path. What I am not able to understand here is that, while we have set the distances to all the vertices as infinity [line number 3], at line 9 we are assigning u := vertex in Q with smallest dist[] but since all the distances are infinite (as set in line number 3) how can there be a smallest distance?
In line 6 it says
dist[source] := 0which makes one of the distances non-infinite. Once that is removed, successive iterations of the loop setdist[v] := alt, creating more non-infinite distances.