Floyd-Warshall Algorithm
–
Pseudocode
1dist[i][j] ← weight of edge i → j (0 if i = j, ∞ if no edge)2for k ← 0 to V − 1: // now allow k as a stop-over3 for i ← 0 to V − 1:4 for j ← 0 to V − 1:5 if dist[i][k] + dist[k][j] < dist[i][j]:6 dist[i][j] ← dist[i][k] + dist[k][j]7if some dist[i][i] < 0: there is a negative cycle
Stop-over k
0
Updates
0
kallowed stop-overi and j (blue)cell just improved
What is the Floyd-Warshall Algorithm?
Floyd-Warshall finds the shortest distance between every pair of vertices at once. It keeps a V × V matrix of distances and improves it with one simple question: would it be shorter to go from i to j via k?
The order matters. Round k allows vertex k as a stop-over, on top of everything allowed before. So after round 0 the matrix knows the best paths through vertex 0, after round 1 through 0 and 1, and after the last round through anything. The whole algorithm is three nested loops.
For each stop-over k: is i → k → j shorter than i → j?
Using the Visualizer
- • The matrix on the right is the answer being built. Row = from, column = to.
- • The highlighted row and column belong to the current stop-over k (yellow vertex). Blue vertices are i and j.
- • Only improvements are shown as separate steps; a green cell just got shorter.
- • Negative edges are allowed. Make a negative cycle in Edit graph and watch a diagonal cell drop below 0.
How It Works
1. Direct edges
Fill the matrix with the edge weights, 0 on the diagonal, ∞ where there is no edge.
2. Pick a stop-over k
Go through k = 0, 1, …, V − 1 in order.
3. Try every pair
If dist[i][k] + dist[k][j] < dist[i][j], take the detour.
4. Check the diagonal
A negative dist[i][i] means i sits on a negative cycle.
Implementation
Properties & Complexity
Time Complexity
- • Always: O(V³), three nested loops
- • Small graphs: very fast in practice, no queues or heaps
Space & Properties
- • Space: O(V²) for the matrix
- • Negative edges: yes
- • Paths: keep a next[][] matrix to rebuild them
Where It Is Used
- • Small dense graphs where all distances are needed
- • Transitive closure: who can reach whom (with true/false instead of numbers)
- • Graph centre: the vertex with the smallest largest distance
Limitations
- • O(V³): too slow for big graphs
- • O(V²) memory even when the graph is sparse
- • Sparse graphs: Johnson's algorithm is faster