Floyd.ppt
Floyd.ppt
Paths Problem
Floyd Warshall
Algorithm
Introduction
•The Floyd-Warshall algorithm
is a dynamic programming
algorithm used to find the
shortest path between all pairs
of vertices in a weighted graph
(directed or undirected).
B 5 D
Path 1: A->B->D =7
Path 2: A->C->D =7 3
Path 3: A->B->C->D =6
2 1
Path 3 is the Shortest path A C
4
(B & C are intermediate
nodes here)
Motive
• Dijkstra's algorithm solves single-source shortest path
problems but is inefficient for all-pairs shortest paths.
Floyd-Warshall efficiently finds shortest paths
between all pairs of vertices in one go.
Used in:
• Network routing for fast data transmission.
• Game development for pathfinding in games.
• used in Google Maps, GPS systems.
Algorithm
Step 1: Construct an adjacency matrix A, where A[i, j]
represents the edge cost.
Set A[i, j] = ∞ if no direct path exists
If i = j (same vertex), set A[i, i] = 0.
Keep the 1st row ,1st column and diagonal elements unchanged Why?
If D[i,k]+D[k,j]<D[i,j],
then update: D[i,j]=D[i,k]+D[k,j]
A1[2, 3]
A0[2, 1]+A0[1, 3]<A0[2, 3]
0 +∞ < ∞ (Condition not Satisfied ❌)
A1[2,4]
A0[2, 1]+A0[1, 4]<A0[2, 4]
0 + 5 < 4 (Condition not
Satisfied ❌)
A1[3,2]
A0[3, 1]+A0[1, 2]<A0[3, 2]
∞ + 3 < 1 (Condition not
Satisfied ❌)
A [3,4]
1
A1[4,1]
A0[4, 2]+A0[2, 1]<A0[4, 1]
∞ + 2 < ∞ (Condition not
Satisfied
A 1
[4,3] ❌)
A0[4, 2]+A0[2, 3]<A0[4, 3]
∞ +∞ < 2(Condition not
Satisfied ❌)
3 as intermediate vertex
4 as intermediate vertex
Final Adjacency Matrix
Complexity:
Time complexity of the Floyd-Warshall
algorithm is O(n³)
The algorithm has three nested loops:
1.Outer loop for selecting an intermediate vertex (k) →
runs n times.
2.Middle loop for selecting a source vertex (i) → runs n
times.
3.Inner loop for selecting a destination vertex (j) →
runs n times.