Algorithms and Computations Complexity: Single-Source Shortest Paths
Algorithms and Computations Complexity: Single-Source Shortest Paths
RELAX(u, v, w)
1 if d[v] > d[u] + w(u, v)
2 then d[v] d[u] + w(u, v)
3 [v] u
The Bellman-Ford algorithm
BELLMAN-FORD(G, w, s)
1 INITIALIZE-SINGLE-SOURCE(G, s)
2 for i 1 to |V[G]| - 1
3 do for each edge (u, v) E[G]
4 do RELAX(u, v, w)
5 for each edge (u, v) E[G]
6 do if d[v] > d[u] + w(u, v)
7 then return FALSE
8 return TRUE
Figure.4: The execution of the Bellman-Ford algorithm. The source is vertex s. The
d values are shown within the vertices, and shaded edges indicate predecessor
values: if edge (u, v) is shaded, then [v] = u. In this particular example, each pass
relaxes the edges in the order (t, x), (t, y), (t, z), (x, t), (y, x), (y, z), (z, x), (z, s), (s, t),
(s, y). (a) The situation just before the first pass over the edges. (b)-(e) The situation
after each successive pass over the edges. The d and values in part (e) are the
final values. The Bellman-Ford algorithm returns TRUE in this example.
Dijkstra's algorithm
DIJKSTRA(G, w, s)
1 INITIALIZE-SINGLE-SOURCE(G, s)
2S
3 Q V[G]
4 while Q
5 do u EXTRACT-MIN(Q)
6 S S {u}
7 for each vertex v Adj[u]
8 do RELAX(u, v, w)
Dijkstra's algorithm relaxes edges as shown in next Figure. Line
1 performs the usual initialization of d and values, and line 2
initializes the set S to the empty set. Line 3 initializes the min-
priority queue Q to contain all the vertices in V ; since S = at
that time, the invariant is true after line 3. Each time through
the while loop of lines 4-8, a vertex u is extracted from Q = V -
S and added to set S, thereby maintaining the invariant. (The
first time through this loop, u = s.) Vertex u, therefore, has the
smallest shortest-path estimate of any vertex in V - S. Then,
lines 7-8 relax each edge (u, v) leaving u, thus updating the
estimate d[v] and the predecessor [v] if the shortest path to v
can be improved by going through u. Observe that vertices are
never inserted into Q after line 3 and that each vertex is
extracted from Q and added to S exactly once, so that the
while loop of lines 4-8 iterates exactly |V| times.