09 Shortest Path
09 Shortest Path
In Graph
Shortest Path in a Graph
A
16 6
10
5 2
B C
-2
8
3 12
E F
14
Bellman Ford Algorithm
Input: Graph G (V, E), Source Vertex: S
Output: Distance [V × V ], Predec [V × V ]
Set Dist[s] := 0
Repeat for all vertices v in V
Repeat for all adjacent nodes t of v
If Dist[t] > Dist[v]+ wt(v,t)
Set Dist[t] := Dist[v]+ wt(v,t)
Set Predec[t] := v
End If
End Repeat
End Repeat
End
Analysis of Algorithm
Procedure Floyd-Warshall(G)
Initialize Dist [V, V] // Initialize from Adj Matrix
Initialize Predec [V, V] // Initialize predecessors
k=0
4
A B
A B C D
7
A 0 999 9 999
B 4 0 999 999
9
C 999 6 0 2
6
C D D 7 999 999 0
2
Floyd Warshall Example
Distance Matrix
k=1
4
A B
A B C D
A 0 999 9 999
7
B 4 0 13 999
9
C 999 6 0 2
C
2
D D 7 999 16 0
k=2
4
A B
A B C D
A 0 999 9 999
7
B 4 0 13 999
9
C 10 6 0 2
C
2
D D 7 999 16 0
k=3
4
A B
A B C D
A 0 15 9 11
7
B 4 0 13 15
9
C 10 6 0 2
C
2
D D 7 22 16 0
k=4
4
A B
A B C D
A 0 15 9 11
7
B 4 0 13 15
9
C 9 6 0 2
C
2
D D 7 22 16 0
B 4 0 13 15
9
C 9 6 0 2
C
2
D D 7 22 16 0
Analysis of Algorithm
Procedure Transitive-Closure(G)
Initialize Dist [V, V] // Initialize from Adj Matrix
A B
A B C D
A 1 0 1 0
B 1 1 0 0
C 0 1 1 1
C D D 1 0 0 1
Transitive Closure Example
Final Distance Matrix
A B
A B C D
A 1 1 1 1
B 1 1 1 1
C 1 1 1 1
C D D 1 1 1 1
Algorithm Types
• Greedy Algorithms:
– Kruskal
– Prim
– Dijkstra
• Dynamic Programming:
– Bellman Ford
– Floyd Warshall
The End