Introduction
Floyd Warshall Algorithm is used to find the shortest distance between every pair of vertices in a graph.
You are given:
- Weighted graph
- Adjacency matrix
Goal:
Find shortest paths between all pairs of nodes.
Unlike Dijkstra and Bellman Ford, Floyd Warshall computes all-pairs shortest paths in a single execution.
Example
Input
Graph Matrix0 3 INF 7
8 0 2 INF
5 INF 0 1
2 INF INF 0
Output
0 3 5 65 0 2 3
3 6 0 1
2 5 7 0
Key Observation
For every pair of nodes (i,j), check whether passing through an intermediate node k produces a shorter path.
Algorithm
- Initialize distance matrix.
- Choose every node as an intermediate node.
- Update shortest paths through that node.
- Repeat for all vertices.
- Final matrix contains shortest distances between all pairs.
Dry Run
Initial Matrix
0 3 INF 7
8 0 2 INF
5 INF 0 12 INF INF 0
Using Node 0
Update paths passing through 0
Using Node 1
Update paths passing through 1
Using Node 2
Update paths passing through 2
Using Node 3
Update paths passing through 3
Final Matrix
0 3 5 65 0 2 3
3 6 0 1
2 5 7 0
Approach : Dynamic Programming
For every pair (i,j), try every possible intermediate node k.
If:
dist[i][k] + dist[k][j] < dist[i][j]then update the shortest distance.