Pseudocode
In the following algorithm, the code u := vertex in Q with smallest dist
, searches for the vertex u
in the vertex set Q
that has the least dist
value. That vertex is removed from the set Q
and returned to the user. dist_between(u, v)
calculates the length between the two neighbor-nodes u
and v
. The variable alt
on lines 20 & 22 is the length of the path from the root node to the neighbor node v
if it were to go through u
. If this path is shorter than the current shortest path recorded for v
, that current path is replaced with this alt
path. The previous
array is populated with a pointer to the "next-hop" node on the source graph to get the shortest route to the source.
If we are only interested in a shortest path between vertices source
and target
, we can terminate the search at line 13 if u = target
. Now we can read the shortest path from source
to target
by reverse iteration:
Now sequence S
is the list of vertices constituting one of the shortest paths from source
to target
, or the empty sequence if no path exists.
A more general problem would be to find all the shortest paths between source
and target
(there might be several different ones of the same length). Then instead of storing only a single node in each entry of previous
we would store all nodes satisfying the relaxation condition. For example, if both r
and source
connect to target
and both of them lie on different shortest paths through target
(because the edge cost is the same in both cases), then we would add both r
and source
to previous
. When the algorithm completes, previous
data structure will actually describe a graph that is a subset of the original graph with some edges removed. Its key property will be that if the algorithm was run with some starting node, then every path from that node to any other node in the new graph will be the shortest path between those nodes in the original graph, and all paths of that length from the original graph will be present in the new graph. Then to actually find all these shortest paths between two given nodes we would use a path finding algorithm on the new graph, such as depth-first search.
Read more about this topic: Dijkstra's Algorithm