Don't memorize Floyd–Warshall — watch the distance matrix improve. Three nested loops let every vertex take a turn as a stepping stone, one at a time. Each turn asks a single question for every pair: is going i → k → j cheaper than the best route we knew? Answer it for all vertices and the matrix fills with every shortest path at once, in O(V³).
dist[i][j] = cheapest cost from i to j found so far. Starts as the raw edges.
INTERMEDIATE k
The vertex we now allow paths to pass through. The outer loop adds one k at a time.
RELAX
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) — try the detour through k.
ALL-PAIRS
After every vertex has been an intermediate, each cell is the true shortest path.
floyd.sim — 4 vertices, directed weighted edges
Ready
Top is a directed weighted graph; below is its distance matrix. Cell (i,j) starts at the direct edge cost, or ∞ if there is no direct road. Press Step to let each vertex become an intermediate and watch the shortcuts appear.
The trick is dynamic programming. Number the vertices 0..V−1 and ask a smaller question: what is the shortest path from i to j that is allowed to pass only through vertices numbered below some limit k? Start with the limit at zero — no intermediates allowed — so the answer is just the direct edge. Then raise the limit one vertex at a time. When you newly permit vertex k, the only paths that could improve are the ones that go through k, and the best such path is dist[i][k] + dist[k][j] using the answers you already have. That is why k sits on the outer loop.
01
Seed with the edges
dist[i][j] = weight of edge i→j, dist[i][i] = 0, and ∞ where no edge exists.
02
Add one intermediate at a time
Outer loop over k. Now paths may hop through vertex k in addition to everything allowed before.
03
Relax every pair
Inner loops over i, j: if dist[i][k] + dist[k][j] < dist[i][j], the detour through k is cheaper — take it.
04
Order is the whole proof
k outermost guarantees dist[i][k] and dist[k][j] already use only earlier intermediates, so combining them is safe.
Time
O(V³)
Space
O(V²)
Negatives
OK
Output
All pairs
Three flat loops, one matrix, no priority queue — Floyd–Warshall is the shortest correct all-pairs code you can write, and it quietly handles negative edges too. It only breaks on a negative cycle, which you can spot afterward: if any diagonal entry dist[i][i] has gone negative, a cycle around i keeps getting cheaper. For single-source paths on a big sparse graph, reach for Dijkstra instead; for all pairs on a small dense one, this is the tool.
Check yourself
1 · Why does the intermediate vertex k go on the outer loop?
The outer k loop is the DP order: when k is added, the two halves of the detour are already optimal over vertices below k, so combining them is correct.
2 · What does one relaxation actually test?
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) — take the detour through k only if it beats what we knew.
3 · How does Floyd–Warshall handle negative weights?
Unlike Dijkstra, it works with negative edges. A negative cycle makes shortest paths undefined; detect it when a diagonal entry turns negative.
The picture: a graph and its finished matrix
A four-vertex directed graph with weights on the edges, and the matrix Floyd-Warshall leaves behind. Row is the start, column is the destination. Highlighted cells are ones that started at ∞ or at a worse edge weight and were improved by routing through another vertex: for instance 0 → 2 has no edge, but costs 5 via vertex 1.
Worked example, step by step
Take four vertices and these directed edges, written [from, to, weight]: [0,1,3] [0,3,7] [1,0,8] [1,2,2] [2,0,5] [2,3,1] [3,0,2]. The table shows, for each value of the outer loop k, which matrix entries got cheaper once vertex k was allowed as a stopover.
Step
Entries improved
Changes (old → new)
seed
-
11 of 16 entries are finite: the diagonal and the 7 edges
k = 0
3
d[1][3]: ∞ → 15; d[2][1]: ∞ → 8; d[3][1]: ∞ → 5
k = 1
2
d[0][2]: ∞ → 5; d[3][2]: ∞ → 7
k = 2
3
d[0][3]: 7 → 6; d[1][0]: 8 → 7; d[1][3]: 15 → 3
k = 3
3
d[1][0]: 7 → 5; d[2][0]: 5 → 3; d[2][1]: 8 → 6
final row 0
-
[0, 3, 5, 6]
final row 1
-
[5, 0, 2, 3]
final row 2
-
[3, 6, 0, 1]
final row 3
-
[2, 5, 7, 0]
Read the k = 2 row. Entry d[1][3] first became 15 at k = 0 (1 → 0 → 3, costing 8 + 7), and two rounds later dropped to 3 (1 → 2 → 3, costing 2 + 1), once vertex 2 was available as a stopover. Each stage only ever uses stopovers numbered at most k, so an entry can improve many times as more stopovers open up, and the last improvement is the true shortest path. Also notice that k = 3 still improved three entries, including d[2][0] (5 → 3, via 2 → 3 → 0): the last vertex in the order is not special, and you cannot stop early because nothing changed in a stage you expected to matter. The finished matrix is the shortest distance between every ordered pair, from one pass of three loops.
Complexity and trade-offs
Case
Time
Space
Why
Floyd-Warshall
O(V³)
O(V²)
Three nested loops over the vertices, one matrix updated in place. Independent of the number of edges.
Dijkstra from every source (binary heap)
O(V · (V+E) log V)
O(V²) to store all results
Faster on sparse graphs, but needs non-negative weights.
Bellman-Ford from every source
O(V² · E)
O(V²)
Handles negative edges; far slower than Floyd-Warshall on dense graphs.
Johnson’s algorithm
O(V · (V+E) log V)
O(V²)
Reweights negative edges with one Bellman-Ford run, then uses Dijkstra from each source.
BFS from every source (unweighted)
O(V · (V+E))
O(V²)
Only valid when every edge costs the same.
Floyd-Warshall wins on dense graphs and on small ones, because its inner loop is a tight array update with no heap and no pointers. It loses on large sparse graphs, where V³ is the bill even if there are only a few edges. The cost is also fixed: a skip such as “do nothing if d[i][k] is ∞” saves work but does not change the bound. On a pseudo-random directed graph with 200 vertices and about 400 edges, the plain loop does 8,000,000 relaxations; skipping the unreachable (i, k) pairs cut that to 1,547,600 (81% of the pairs skipped), but it is still millions of steps for a graph that is nearly empty. Doubling V multiplies the work by eight, so the method stops being practical in the low thousands of vertices. It also stores the whole V × V matrix, which is a memory limit before it is a time one.
Common mistakes
Putting k anywhere but the outer loop
The order k, i, j is the algorithm. Writing i, j, k looks equivalent and returns plausible matrices. On the graph above it gets one entry wrong: d[1][0] = 7 instead of 5. With k innermost, a pair is finished before the stopovers it depends on have been combined.
Leaving the diagonal at ∞
Every d[i][i] must start at 0. If you only fill in the edges, the diagonal becomes the length of the cheapest cycle through the vertex: on the graph above all four diagonal entries come out as 8, so “distance from a vertex to itself” is wrong, and so is any answer that routes through it.
Using a “big number” that overflows
Code like INF = 2147483647 in a 32-bit integer fails on d[i][k] + d[k][j]: two infinities add to -2, which looks like a very short path and wins the comparison. Either skip when either side is infinite, or choose an INF no larger than half the integer maximum.
Ignoring negative cycles
Negative edges are fine, but a negative cycle makes shortest paths undefined. For edges 0→1 (1), 1→2 (−3), 2→0 (1) the loop costs −1, and the algorithm ends with d[0][0] = -1 and d[2][2] = -2. Check the diagonal for a negative value after the run and refuse to trust any row that reaches such a vertex.
Assigning duplicate edges instead of taking the minimum
Input may list the same pair twice. For [0,1,2] followed by [0,1,5], plain assignment leaves d[0][1] = 5, not 2. Seed with d[u][v] = min(d[u][v], w).
Where this shows up
Precomputed routing and distance tables
When the graph is small and queried often, such as the stations of a transit map or the rooms of a game level, computing every pair once makes each later lookup a single array read.
Transitive closure
Replace the numbers with booleans and min, + with or, and: the same triple loop (Warshall’s form) answers “can A reach B?” for every pair, which is what reachability checks on dependency graphs need.
Detecting arbitrage
Turn each exchange rate r into the edge weight −log r. A cycle whose rates multiply to more than 1 becomes a negative cycle. With the made-up rates 0.9, 0.9 and 1.3 (product 1.053), the run gives d[0][0] = -0.0516, a negative diagonal, which flags the loop.
Graph statistics
Eccentricity, diameter and closeness centrality all need every pairwise distance. On networks small enough for a V × V matrix, Floyd-Warshall gives the full table in one go.
SOLVE IT YOURSELF
Solve it: all-pairs shortest paths
Three nested loops, and every shortest path in the graph falls out. Write it in Python or TypeScript, running for real in your browser. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Hints are below, and Reveal solution is one click away.
YOUR TASK
Implement shortest_paths(n, edges): given n vertices (0…n-1) and a list of directed[u, v, w] edges, return an n × n matrix where entry [i][j] is the shortest distance from i to j — 0 on the diagonal, and infinity where no path exists.
HINTS — 5 IDEAS
Start with dist[i][j] = ∞ everywhere, then dist[i][i] = 0 — a vertex reaches itself for free.
Lay in each edge: dist[u][v] = min(dist[u][v], w). The min matters — a graph may list the same pair twice.
The key loop order is k outermost: "using only vertices 0…k as intermediates, what is the best i→j?"
Relax: if dist[i][k] + dist[k][j] < dist[i][j], you found a better route through k — take it.
Getting k inner instead of outer is the classic bug: it silently returns wrong answers on some graphs, not all.
CPython · WebAssembly✓ Solved
1
1
▶ Watch it explained
Floyd-Warshall: Time and Space Complexity, From First Principles
Questions
Floyd–Warshall vs running Dijkstra from every vertex?
Both give all-pairs shortest paths. Floyd–Warshall is O(V³) with tiny constants and trivial code, ideal for small or dense graphs and it allows negative edges. Dijkstra-from-each-source is roughly O(V·E log V), which wins on large sparse graphs — but only with non-negative weights.
How do I reconstruct the actual path, not just the cost?
Keep a second matrix next[i][j] = the first vertex on the path. Initialise it to j for each edge, and whenever a relaxation through k succeeds, set next[i][j] = next[i][k]. Follow next[i][j] to walk the path.
How do I detect a negative cycle?
Run the algorithm, then scan the diagonal. If any dist[i][i] is negative, vertex i sits on a cycle whose total weight is below zero, so no finite shortest path exists for pairs that can reach it.
Every pair, one triple loop.
Let each vertex be a stepping stone in turn, relax every pair, and the whole matrix settles into the shortest paths — O(V³), negatives welcome.