Professional Documents
Culture Documents
Nptel Week4 Module3 Bellman Ford PDF
Nptel Week4 Module3 Bellman Ford PDF
Week 4, Module 3
Burnt vertices v
x
s y
w
Burnt vertices v
x
s y w
s→ v1 → v2 → v3 … → vm → t
Dijkstra’s algorithm
Update is safe
s→ v1 → v2 → v3 … → vm → t
Iteration 1
…
update(s,v1)
…
update(v1,v2)
…
update(v2,v3)
…
update(vm,t)
…
Bellman-Ford algorithm
Initialize Distance(s) = 0, Distance(u) = ∞ for all other vertices
Iteration 1 Iteration 2
… …
update(s,v1) update(s,v1)
… …
update(v1,v2) update(v1,v2)
… …
update(v2,v3) update(v2,v3)
… …
update(vm,t) update(vm,t)
… …
Bellman-Ford algorithm
Initialize Distance(s) = 0, Distance(u) = ∞ for all other vertices
Iteration 1 Iteration 2 …
… … …
update(s,v1) update(s,v1) …
… … …
update(v1,v2) update(v1,v2) …
… … …
update(v2,v3) update(v2,v3) …
… … …
update(vm,t) update(vm,t) …
… … …
Bellman-Ford algorithm
Initialize Distance(s) = 0, Distance(u) = ∞ for all other vertices
for i = 1 to n
Distance[i] = infinity
Distance[s] = 0
8 -4 3
1 2 1
7 -2 4
-1 3
6 -1
5
Example
10
1 2
8 1
1
2
8 -4 3 3
1 2
Node
1 4
5
7 -2 4
6
-1 3 7
6 -1
5 8
Example
Iteration
10 0
1 2
8 1 0
1
2 ∞
8 -4 3 3 ∞
1 2
Node
1 4 ∞
5 ∞
7 -2 4
6 ∞
-1 3 7 ∞
6 -1
5 8 ∞
Example
Iteration
10 0 1
1 2
8 1 0 0
1
2 ∞ 10
8 -4 3 3 ∞ ∞
1 2 ∞
Node
1 4 ∞ ∞
5 ∞ ∞
7 -2 4
6 ∞ ∞
-1 3 7 ∞ ∞
6 -1
5 8 ∞ 8
Example
Iteration
10 0 1 2
1 2
8 1 0 0 0
1
2 ∞ 10 10
8 -4 3 3 ∞ ∞ ∞
1 2 ∞
Node
1 4 ∞ ∞ ∞
5 ∞ ∞ ∞
7 -2 4
6 ∞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