Five warehouses, nine roads, and one road that pays you 5. Floyd-Warshall fills all 25 cheapest costs with 125 small checks. Watch 1 → 3 fall from 8 to 5 to −1.
Drag k to allow one more warehouse as a stop. Tap any cell to see its route. Then we build, piece by piece, the matrices, the min-plus product, Floyd-Warshall, path recovery, reachability, Johnson's reweighting and the negative-cycle check.
You need a little Python and the idea of a shortest path from one start (CLRS 24 teaches it). We build the rest from zero.
Based on Chapter 25, All-Pairs Shortest Paths, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Single-Source Shortest Paths. Next: Maximum Flow.
Illustrative toy graph. Purple cells dropped at this k. The warm ring is the newest allowed stop. 5 values of k × 25 cells = 125 checks.
Chapter 0
Price a table of every start and every end, and count what the obvious plan costs
You run five warehouses. Each morning you need the cheapest shipping cost from every warehouse to every other one: a full price list of 25 cells. One road, 4 → 3, carries a subsidy, so it costs −5. That is the all-pairs shortest paths problem: the cheapest route between every ordered pair of vertices.
The obvious plan reuses single-source shortest paths: run it once from every vertex. With a negative road, Dijkstra is not allowed, so each run is Bellman-Ford (relax every road V − 1 times). V runs of it cost about V × V × E steps, where V is the number of vertices and E the number of roads.
Drag the number of cities. Pick sparse or dense roads. The axis is logarithmic: one grid line is ten times more work.
Step counts drop constant factors. Dijkstra and Johnson use a binary heap here. The hollow bar is Dijkstra from every city: it gives wrong costs when a road is negative.
Worked number: 1,000 cities, 5 roads each, so E = 5,000. Bellman-Ford from every city costs 1,000 × 1,000 × 5,000 = 5 × 109 steps. Floyd-Warshall costs 1,0003 = 109. Johnson's algorithm costs about 6.5 × 107. The rest of this lesson builds the last two.
The failure. Symptom: an all-pairs job on a map with a few negative roads returns costs that are too high. Measure: compare one row with a Bellman-Ford run from that row's start. Fix: the code ran Dijkstra on negative roads; use Floyd-Warshall or Johnson instead.
Chapter 1
Write the roads as a table, then define the table we want back
Number the warehouses 1 to 5. The input is the weight matrix W, a 5 × 5 table. Row i, column j holds the cost of the direct road from i to j. The diagonal is 0. A missing road is ∞, which means "no direct road".
The output is the distance matrix D: row i, column j holds the cheapest cost of any route from i to j. Next to it sits the predecessor matrix Π (pi): the warehouse just before j on that cheapest route. D answers "how much". Π answers "which way".
Switch between W and D. Tap a cell: the map lights the road, or the whole route, that the cell describes.
The same toy graph as the hero. Rows are the start, columns the end.
A path is a list of vertices where each step uses a road. Its weight is the sum of its road costs. Call the cheapest weight from i to j δ(i, j), said "delta of i, j".
Delta of i, j equals the minimum over paths p, of the sum over t, of w of v-t-minus-one, v-t.
For each path p from i to j, add the road costs w of its steps. The smallest total is δ(i, j). If no path exists, δ(i, j) is ∞.
From 1 to 3 there are four simple paths: 8 (direct), 3 + 2 = 5, 3 + 1 − 5 = −1, and 7 + 6 − 5 = 8. So δ(1, 3) = −1, by 1 → 2 → 4 → 3.
Listing every path is hopeless at scale: their number grows faster than any power of V. The algorithms ahead never list paths. They fill the table by reusing cells they already know.
The failure. Symptom: the table says 0 where no road exists. Measure: print W; a missing road should read ∞, not 0. Fix: fill W with ∞ first, then 0 on the diagonal, then the roads.
Chapter 2
Extend every cheapest route by one road, and see matrix multiplication with new operations
Suppose you know the cheapest cost from i to every vertex using at most m − 1 roads. How do you get the best with at most m roads? Try every last stop k. Pay the best cost to k, then the direct road from k to j. Keep the smallest.
Call the table of cheapest costs that use at most m roads L(m), said "L-m". L(1) is W itself.
L-m of i, j equals the minimum over k of L-m-minus-one of i, k, plus w of k, j.
For each candidate last stop k, add the old best cost L(m−1)[i][k] and the road w[k][j]. The smallest of the five sums is L(m)[i][j].
L(3)[1][3], with row 1 of L(2) = 0, 3, 5, 4, 7. The five sums are 0 + 8 = 8, 3 + 2 = 5, 5 + 0 = 5, 4 + (−5) = −1 and 7 + ∞ = ∞. The minimum is −1, through stop 4.
Pick a pair and a road budget m. Each bar is one candidate last stop k. The shortest bar wins.
Values come from the toy graph. A bar that reaches ∞ means no route of that length exists.
Look at the shape. Ordinary matrix multiplication computes C[i][j] as the sum over k of A[i][k] times B[k][j]. Here the sum becomes a minimum and the product becomes a plus. CLRS calls this the min-plus product and writes it L(m) = L(m−1) ⊗ W.
The failure. Symptom: an extra product changes a cell that should be final. Measure: check the diagonal; a value below 0 means a negative cycle. Fix: stop and report the cycle (Chapter 9).
Chapter 3
Double the road budget with each product instead of adding one road
A cheapest path never repeats a vertex when there is no negative cycle. So it uses at most n − 1 roads, where n is the number of vertices, and L(n−1) = D. Adding one road at a time takes n − 2 products. Each product costs n3 steps, so the total is about n4.
The fix: multiply the table by itself. A route of at most 2m roads splits into two halves of at most m roads each.
L-two-m equals L-m, min-plus times L-m.
Square L(1) to get L(2), square that to get L(4), and go on. Stop once 2m reaches n − 1. That takes ⌈log₂(n − 1)⌉ products: the number of doublings from 1 to n − 1, rounded up.
n = 5: log₂ 4 = 2 products, L(1) → L(2) → L(4). n = 1,000: ⌈log₂ 999⌉ = 10 products instead of 998. Each costs 109 steps, so the run drops from about 1012 to 1010.
Pick a plan and press Step. Purple cells changed with this product. The counter shows how many products you paid.
Toy graph, n = 5. Overshooting is safe: once m ≥ n − 1, more products change nothing.
Squaring works because the min-plus product is associative: (A ⊗ B) ⊗ C equals A ⊗ (B ⊗ C), as with ordinary products. The result is O(n3 log n). That is still slower than the next chapter's O(n3), but any faster min-plus product would speed up all-pairs shortest paths at once. Nobody knows a truly sub-cubic one for general weights.
The failure. Symptom: squaring stops early and leaves ∞ in reachable cells. Measure: check that the last power is at least n − 1. Fix: loop while m < n − 1.
Chapter 4
Grow the set of allowed stops, not the number of roads, and drop the log factor
Change the question. An intermediate vertex of a path is any vertex on it except the two ends. Ask: what is the cheapest route from i to j if only warehouses 1 to k may be intermediate? Call it d(k)[i][j]. With k = 0, only direct roads count, so d(0) = W.
Now allow warehouse k. The best route either skips k, and costs what it did before, or passes through k once. Then it splits into i to k and k to j, and each half uses only stops 1 to k − 1.
d-k of i, j equals the minimum of d-k-minus-one of i, j, and d-k-minus-one of i, k plus d-k-minus-one of k, j.
For the new stop k and every pair (i, j): add the cost i to k and the cost k to j. If the sum beats the old d[i][j], write it in. After k = n, every vertex may be a stop, and the table is D.
k = 4, cell (1, 3): the old best is 5 (via 2). The route through 4 costs d[1][4] + d[4][3] = 4 + (−5) = −1. min(5, −1) = −1, so the cell drops to −1.
Pick a cell. The staircase shows its value at every k. Drag k to read the two options at that step.
Toy graph. The step at each k compares the two options of the recurrence.
This is dynamic programming: the state is (i, j, k), and each answer reuses two answers from the layer k − 1. There are n layers of n2 cells and each cell costs one addition and one comparison. That is Θ(n3), with no heap and no log factor.
The failure. Symptom: a cell stays ∞ though a route exists. Measure: check that k runs over all n vertices, 0 to n − 1 in Python. Fix: a loop like range(1, n) skips vertex 0 as a stop.
Chapter 5
Put k outside, update in place, and watch the wrong order miss a cell
The whole algorithm is three loops. k must be the outer loop, because layer k needs all of layer k − 1 first.
pythondef floyd_warshall(W): n = len(W) d = [row[:] for row in W] # d(0) = W for k in range(n): # the new stop: OUTER for i in range(n): for j in range(n): if d[i][k] + d[k][j] < d[i][j]: d[i][j] = d[i][k] + d[k][j] return d
Why is one table enough? During layer k, row k and column k never change. For example, the new d[i][k] is min(d[i][k], d[i][k] + d[k][k]), and d[k][k] = 0. So reading a cell that this layer already rewrote gives the same answer as reading the old layer.
Pick a loop order and press Run pass. Red cells disagree with the true D.
Toy graph. One pass is the full triple loop over n3 = 125 checks.
Worked number. With k inside, the loop finishes cell (1, 3) before cell (1, 4) has learned the route 1 → 2 → 4. So (1, 3) stops at 5, the route 1 → 2 → 3. The true cost is −1. On this graph, a second pass of the wrong order repairs it. Hide, Kumabe and Maehara (2019) proved that three passes of the wrong order always give the right table, but one pass does not.
The failure. Symptom: most cells are right and a few are too high. Measure: compare with a second run or a Bellman-Ford row. Fix: put k outermost.
Chapter 6
Store one pointer per cell, then walk it backwards from the end
D gives the cost, not the route. Keep a second table, Π. Cell Π[i][j] holds the vertex just before j on the best route from i. At the start, Π[i][j] = i if a direct road exists, and NIL (no value) otherwise.
When the route through k wins, the last road of the new route is the last road of the half from k to j. So j's predecessor comes from row k, not from k itself.
pi-k of i, j equals pi-k-minus-one of k, j, if the route through k is cheaper. Else it equals pi-k-minus-one of i, j.
Whenever the cost d[i][j] drops through k, copy the pointer π[k][j] into π[i][j]. To print a route, start at j and follow π[i][·] back until you reach i. Then reverse the list.
At k = 4, cell (1, 3) drops to −1, so π[1][3] = π[4][3] = 4. Walk back: π[1][3] = 4, π[1][4] = 2, π[1][2] = 1. The route is 1 → 2 → 4 → 3, and 3 + 1 − 5 = −1.
Pick a pair. Switch between the correct update and the bug that stores k. Red marks a road that does not exist.
Toy graph. The pointer row under the map is Π[i][·] for the chosen start i.
A walk visits at most n vertices, so one route costs O(n) and all n2 routes cost O(n3). That is no more than Floyd-Warshall itself.
The failure. Symptom: a printed route uses a road that is not on the map. Measure: check every hop against W and add the hop costs; the sum must equal D[i][j]. Fix: set π[i][j] = π[k][j], not k.
Chapter 7
Keep the same three loops, and swap min and plus for OR and AND
Sometimes the cost does not matter, only whether any route exists. Which modules does a module depend on, directly or through others? The transitive closure of a directed graph is a 0-or-1 table T: T[i][j] = 1 exactly when some path leads from i to j. Every vertex reaches itself.
Floyd-Warshall answers it if you check which cells end below ∞. CLRS gives a lighter version, often credited to Warshall: the same loops with yes-or-no values. Call the reachability with stops 1 to k allowed t(k)[i][j].
t-k of i, j equals t-k-minus-one of i, j, or, t-k-minus-one of i, k and t-k-minus-one of k, j.
For the new stop k: every i that reaches k now also reaches everything k reaches. Start from t(0): 1 on the diagonal and on each road.
Roads A→B, B→C, B→D, D→A, D→C, E→D. At k = D: t[E][D] = 1 and t[D][A] = 1, so t[E][A] = 0 ∨ (1 ∧ 1) = 1.
Drag k through A to E. Blue cells are 1. Purple cells turned to 1 at this step.
Illustrative graph of six roads. The final table has 18 ones out of 25.
The cost stays Θ(n3), but each cell is one bit. Store a row as the bits of one integer. Then "every i that reaches k gets k's row" is one OR of whole rows: if row[i] has bit k: row[i] |= row[k]. A 64-bit word handles 64 cells per operation.
The failure. Symptom: a vertex does not reach itself. Measure: check the diagonal of t(0). Fix: set T[i][i] = 1 before the loops.
Chapter 8
Shift every road by a height difference so none is negative, then run Dijkstra from every vertex
On a sparse map, Dijkstra from every vertex beats n3, but a negative road breaks Dijkstra. Adding a constant to every road fails: a route with more roads gains more. Johnson gives each vertex a potential h(v), a height. Each road shifts by the height of its start minus the height of its end.
w-hat of u, v equals w of u, v, plus h of u, minus h of v.
Add a vertex s with a road of cost 0 to every vertex. Run Bellman-Ford from s; its costs are h. Each new cost w-hat is w plus h(u) minus h(v).
Bellman-Ford gives h = 0, −1, −5, 0, 0. Road 4 → 3: −5 + 0 − (−5) = 0. Road 1 → 3: 8 + 0 − (−5) = 13. All nine new costs are 0 or more.
Why 0 or more? h holds shortest costs from s, so it obeys the triangle inequality. The best cost to v is at most the best cost to u plus the road u → v.
h(v) ≤ h(u) + w(u, v), so w(u, v) + h(u) − h(v) ≥ 0.
Why do best routes stay best? Add the new costs along a path v0, …, vq with original weight w(p). Each inner height appears once with a plus and once with a minus, so only the ends survive.
w-hat of p equals w of p, plus h of v-zero, minus h of v-q.
Every path from u to v shifts by h(u) minus h(v), so the cheapest path stays the cheapest. To undo, subtract h(u) and add h(v).
Path 1 → 2 → 4 → 3: w(p) = −1, and its new cost is 4 + 0 + 0 = 4 = −1 + 0 − (−5). Dijkstra finds 4. Undo: 4 − h(1) + h(3) = 4 − 0 − 5 = −1.
Step through the phases and pick a source. Then switch to the naive fix and watch the wrong route win.
Toy graph. Bellman-Ford relaxes the roads in code-lab order: pass 1 sets h(3), pass 2 sets h(2).
The cost is one Bellman-Ford run, O(VE), plus V Dijkstra runs. CLRS uses a Fibonacci heap, for O(V2 log V + VE) in total. Worked number: V = 10,000 and E = 50,000. Floyd-Warshall pays 1012 steps; Johnson pays about 2.3 × 109.
The failure. Symptom: Dijkstra returns a route that is not the cheapest. Measure: scan the new costs for a negative one. Fix: shift by h(u) − h(v) from Bellman-Ford, not by a constant.
Chapter 9
Read the diagonal to find a loop that pays you, and stop
A negative cycle is a loop of roads whose costs sum below 0. Go around it again and the cost drops again, with no floor. Pairs that can route through it have no shortest path: their true cost is −∞.
After Floyd-Warshall, the diagonal tells you. d[i][i] starts at 0, the empty path. It can only drop below 0 if some round trip from i back to i costs less than nothing.
A negative cycle exists if and only if there is some i with d of i, i less than zero.
Run Floyd-Warshall. Scan the diagonal. If any d[i][i] is below 0, a negative cycle exists, and the numbers in D are not true costs.
Make road 4 → 3 cost −6. The loop 2 → 4 → 3 → 2 costs 1 − 6 + 4 = −1. The diagonal reads 0, −1, −1, −2, 0: vertices 2, 3 and 4 sit on the loop.
Drag the cost of road 4 → 3. The loop 2 → 4 → 3 → 2 sums to 5 plus that cost. Watch the diagonal.
Toy graph. With a negative cycle, the values Floyd-Warshall prints off the diagonal depend on loop order; the true costs are −∞.
Johnson's algorithm finds the same thing earlier: Bellman-Ford from s reports a negative cycle when it can still relax a road after V − 1 passes. Then the algorithm stops.
One use is currency arbitrage. Take made-up rates: dollars to euros 0.85, euros to pounds 0.88, pounds to dollars 1.40. One dollar becomes 0.85 × 0.88 × 1.40 = 1.047 dollars. Give each trade the cost −ln(rate). Then the loop costs 0.163 + 0.128 − 0.336 = −0.046, and a negative cycle is a profit loop.
The failure. Symptom: a route printer never ends. Measure: scan the diagonal before printing. Fix: report the cycle and print no routes for pairs that touch it.
Chapter 10
Keep the choices, the numbers, the checks and the core code on one page
All-pairs shortest paths fills a table of the cheapest cost for every ordered pair. Floyd-Warshall allows one more stop per layer and costs Θ(V3) on any graph. Johnson lifts every road to 0 or more with Bellman-Ford potentials, then runs Dijkstra from every vertex: the better choice on sparse maps. Both report negative cycles.
| Plan | Time | Negative roads? | Use it when |
|---|---|---|---|
| Dijkstra from every vertex | O(V2 log V + VE), Fibonacci heap | No | every road costs 0 or more |
| Bellman-Ford from every vertex | O(V2E) | Yes | rarely: Johnson does the same job faster |
| Repeated squaring | Θ(V3 log V) | Yes | you study the min-plus algebra |
| Floyd-Warshall | Θ(V3) | Yes | the graph is dense or small; ten lines of code |
| Johnson | O(V2 log V + VE), Fibonacci heap | Yes | the graph is sparse and has negative roads |
| Term | Meaning | Number on this page |
|---|---|---|
| W, D, Π | direct roads in; cheapest costs and predecessors out | D[1][3] = −1, D[3][1] = 7 |
| Min-plus product | sum becomes min, times becomes plus | L(3)[1][3] = −1 |
| Repeated squaring | L(2m) = L(m) ⊗ L(m) | 10 products for n = 1,000, not 998 |
| Floyd-Warshall layer k | stops 1 to k allowed | 9 cells drop at k = 4, none at k = 5 |
| Predecessor update | π[i][j] = π[k][j] | 5 → 4 → 3 → 2, cost 5 |
| Transitive closure | OR and AND in place of min and plus | 18 ones of 25 |
| Potential h | Bellman-Ford costs from a new source s | h = 0, −1, −5, 0, 0 |
| Reweighting | w + h(u) − h(v), never negative | road 4 → 3: −5 becomes 0 |
| Negative cycle | some d[i][i] < 0 | road 4 → 3 at −6: loop costs −1 |
pythonINF = float('inf') def all_pairs(n, roads): """roads: (u, v, w) with 0-indexed vertices. Returns (d, pi), or None on a negative cycle.""" d = [[INF] * n for _ in range(n)] pi = [[None] * n for _ in range(n)] for i in range(n): d[i][i] = 0 for u, v, w in roads: if w < d[u][v]: # keep the cheapest parallel road d[u][v], pi[u][v] = w, u for k in range(n): # the new stop: outer loop for i in range(n): for j in range(n): if d[i][k] + d[k][j] < d[i][j]: d[i][j] = d[i][k] + d[k][j] pi[i][j] = pi[k][j] # not k if any(d[i][i] < 0 for i in range(n)): return None # negative cycle return d, pi def route(pi, i, j): if i == j: return [i] if pi[i][j] is None: return [] out = [j] while out[-1] != i: out.append(pi[i][out[-1]]) return out[::-1] roads = [(0,1,3), (0,2,8), (1,2,2), (1,3,1), (2,1,4), (3,0,2), (3,2,-5), (0,4,7), (4,3,6)] d, pi = all_pairs(5, roads) print(d[0][2], route(pi, 0, 2)) # -1 [0, 1, 3, 2] (1 -> 2 -> 4 -> 3)
Now press Present or Teach. Explain from memory the two options at each k, why π[i][j] copies π[k][j], and why Johnson's shift keeps the cheapest route. Then go back to the hero, drag k from 0 to 5, and say which stop dropped 1 → 3 to −1.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 25, All-Pairs Shortest Paths (third edition numbering). The recurrences and running times follow the book; the toy graph, the devices and the step counts are our own. The three-pass result is from T. Hide, S. Kumabe and T. Maehara, "Incorrect implementations of the Floyd-Warshall algorithm give correct solutions after three repeats" (2019).