Lecture 23
Lecture 23
1
Class Overview
➢ The shortest path problem
➢ Differences
➢ Time complexity
2
Shortest Path Problem
➢ Weighted path length (cost): The sum of the weights of all
links on the path.
3
Differences
➢ Negative link weight: The Bellman-Ford algorithm works;
Dijkstra’s algorithm doesn’t.
4
The Bellman-Ford Algorithm
t x
5
6 ,nil -2 ,nil
-3
0 8
s -4 7
2
7
,nil 9 ,nil
y z
5
The Bellman-Ford Algorithm
t x t x
5 5
6 ,nil ,nil 6 6,s -2 ,nil
-2
-3 -3
0 8 0 8
s -4 7 s -4 7
2 2
7 7
,nil ,nil 7,s 9 ,nil
9
y Initialization z y After pass 1 z
t x t x
5 5
6 6,s -2 4,y 6 2,x 4,y
-2
-3 -3
0 8 0 8
s -4 7 s -4 7
2 2
7 7
7,s 9 2,t 7,s 2,t
9
y After pass 2 z
y After pass 3 z
The order of edges examined in each pass:
(t, x), (t, z), (x, t), (y, x), (y, t), (y, z), (z, x), (z, s), (s, t), (s, y)
6
The Bellman-Ford Algorithm
t x
5
6 2,x -2 4,y
-3
0 8
s -4 7
2
7
7,s 9 -2,t
y z
After pass 4
7
The Bellman-Ford Algorithm
Bellman-Ford(G, w, s)
1. Initialize-Single-Source(G, s)
2. for i := 1 to |V| - 1 do
3. for each edge (u, v) E do
4. Relax(u, v, w)
5. for each vertex v u.adj do
6. if d[v] > d[u] + w(u, v)
7. then return False // there is a negative cycle
8. return True
Relax(u, v, w)
if d[v] > d[u] + w(u, v)
then d[v] := d[u] + w(u, v)
parent[v] := u
8
Time Complexity
Bellman-Ford(G, w, s)
1. Initialize-Single-Source(G, s) O(|V|)
2. for i := 1 to |V| - 1 do
3. for each edge (u, v) E do
O(|V||E|)
4. Relax(u, v, w)
5. for each vertex v u.adj do O(|E|)
6. if d[v] > d[u] + w(u, v)
7. then return False // there is a negative cycle
8. return True
9
Bellman-Ford
Algorithm
Bellman-Ford Algorithms