Floyd-Warshall Algorithm
@floydwarshall_algorithmPseudo-code
function floyd_warshall(d):
# Step 1: Try every node as an intermediate
for k from 0 to n-1:
# Step 2: Check all pairs (i, j)
for i from 0 to n-1:
for j from 0 to n-1:
# Step 3: Relax using node k
if d[i][k] + d[k][j] < d[i][j]:
d[i][j] = d[i][k] + d[k][j]
return d
- d A distance matrix where d[i][j] stores the shortest distance from node i to node j.
- i Starting node of a path.
- j Ending node of a path.
- k Intermediate node we try to use to improve the path from i to j.
- INF A very large value representing infinity, used when no direct path exists.
Recipe Steps
Start with a table — Imagine a table where you write the distance between every pair of cities.
Pick a middle city — Ask: 'Can going through this city make any route shorter?'
For every pair of cities (A to B), check if A → middle → B is shorter than the current path.
If yes, update the distance in the table.
Repeat this for every possible middle city until no improvements can be made.
Questions & Answers
- Works well when you need all-pairs shortest paths.
- Tip: Think of it as gradually improving a full distance table.
- Common mistake: Forgetting to initialize d[i][i] = 0.
- If d[i][i] becomes negative, it means there is a negative cycle.
Related Algorithms
Bellman-Ford Algorithm
The Bellman-Ford algorithm finds the shortest path from a source node to all other nodes, even when there are negative edge weights. It works by repeatedly improving distance estimates.
ViewDijkstra's Algorithm
Dijkstra's Algorithm finds the shortest path from one starting node to all other nodes in a graph by always expanding the currently closest node first.
ViewDinic's Algorithm
Dinic's Algorithm finds the maximum flow in a network by building layers using BFS and then sending flow using DFS in these layers, making it faster than simpler methods.
View