Analysis of Algorithms: The Bellman-Ford Algorithm
Analysis of Algorithms: The Bellman-Ford Algorithm
Mohammed Hussein
Analysis of Algorithms
1
2
Introduction to the Bellman-
Ford Algorithm
6
7
4 8
7 3
5
9 4
8
2
6
Shortest path: 0 1 4 5
Dr. Mohammed Hussein
17
8
ex2
6
7
4 18
7 3
5
9 4
8
2
6
Shortest path: 0 1 2 3 4 5
6
7
4 -18
7 3
5
9 4
8
2
6
Shortest path: 0 1 4 5
7
4 Update
2
1 If (d[u]+c(u,v)<d[v])
2 d[v]= d[u]+c(u,v)
1 2 6
0 1
4 5
3 5
3
⮚ Weighted path length (cost): The sum of the weights of all links on the
path.
https://onlinegdb.com/8fUjfHcFH
pseudocode
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. Update (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 Update (u, v, w)
if d[v] > d[u] + w(u, v)
then d[v] := d[u] + w(u, v)
Dr. Mohammed Hussein
parent[v] := u
18
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
4. Relax(u, v, w) O(|V||E|)
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
Dr. Mohammed Hussein
-2
0 4
4 -nf
1 2
5 -10
4 3
5 3 8 V d[v]
-nf -nf 1 0
Edge= (1,4),(1,2),(4,3),(3,2) 2 -2
3 8
4 5
Dr. Mohammed Hussein
Example directed weighted graph
0
1
2
3
5
6
-1 -nf
-nf 5
2
3
6 -2 3
1 7 5
5 3 3
0 1 7
5 3 8
5 -2
-nf -nf
6
4 -1 4
5
-nf -nf
results
Relaxation -1
5
If (d[u]+c(u,v)<d[v]) 2 O(E*(V-1))
d[v]= d[u]+c(u,v) 3
-2 O(E*V)
6
V d[v 1 O(n^2)
7
] 5 3
0 1
1 0 3
2 1 5 -2
3 3
6
4 5 4 -1
5 0
6 4 Edge= (1,2),(1,3), (1,4),(2,5), (3,2),(3,5), (4,3),(4,6) , (5,7),(6,7)
7 3
Dr. Mohammed Hussein
22
homework
4
1 2
5 5 -10
4 3
3