All-Pairs Shortest Paths

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.

Allow one more stop

0

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

Every Pair at Once

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.

Count the work

Drag the number of cities. Pick sparse or dense roads. The axis is logarithmic: one grid line is ten times more work.

1,000

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.

The road

  1. The matrices: W goes in, D and Π come out.
  2. One more road: the min-plus product.
  3. Repeated squaring: fewer products by doubling.
  4. Floyd-Warshall: allow one more stop. The hero's k slider.
  5. Loop order: why k must be the outer loop.
  6. Path recovery: the hero's tapped route.
  7. Transitive closure: yes or no instead of a cost.
  8. Johnson's algorithm: lift every road to zero or more (the showcase).
  9. Negative cycles: when the table has no answer.
  10. The field guide: terms, numbers, code and the credit.
A map has 2,000 cities, 3 roads per city, and a few roads with negative cost. Which plan does the least work?

Chapter 1

The Matrices: W In, D and Pi Out

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".

Read a cell on the map

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".

Say it aloud

Delta of i, j equals the minimum over paths p, of the sum over t, of w of v-t-minus-one, v-t.

δ(i, j)
delta of i, j the cheapest cost from i to j. It fills cell (i, j) of D.
minp
the minimum over paths p try every path p that starts at i and ends at j; keep the smallest total.
Σt
the sum over t one term for each step t of the path.
w(vt−1, vt)
w of v-t-minus-one, v-t the cost of the road used at step t, from the vertex before to the vertex after.
In plain words

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 ∞.

With numbers

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.

W[3][1] is ∞ but D[3][1] is 7. What does that mean?

Chapter 2

One More Road: the Min-Plus Product

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.

Say it aloud

L-m of i, j equals the minimum over k of L-m-minus-one of i, k, plus w of k, j.

L(m)[i][j]
L-m of i, j the cheapest cost from i to j using at most m roads.
mink
the minimum over k try every vertex k as the last stop before j, k = 1 to 5.
L(m−1)[i][k]
L-m-minus-one of i, k the best cost from i to k with one road fewer.
w[k][j]
w of k, j the direct road from k to j. It is 0 when k = j, so "stay put" is one of the choices.
In plain words

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].

With numbers

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.

Compute one cell

Pick a pair and a road budget m. Each bar is one candidate last stop k. The shortest bar wins.

3

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).

In the min-plus product, which operations replace the plus and the times of ordinary matrix multiplication?

Chapter 3

Repeated Squaring

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.

Say it aloud

L-two-m equals L-m, min-plus times L-m.

L(2m)
L-two-m the cheapest costs using at most 2m roads.
L(m)
L-m the cheapest costs using at most m roads: the first half of the route.
⊗
min-plus times the product of Chapter 2: for each middle vertex k, add the two halves, keep the minimum.
L(m)
L-m the same table again: the second half, from k to j.
In plain words

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.

With numbers

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.

Grow the table

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.

A graph has 17 vertices and no negative cycle. How many squarings take L(1) to a table equal to D?

Chapter 4

Floyd-Warshall: Allow One More Stop

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.

Say it aloud

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.

d(k)[i][j]
d-k of i, j the cheapest cost from i to j when we allow stops 1 to k.
min
the minimum of keep the cheaper of the two options.
d(k−1)[i][j]
d-k-minus-one of i, j option one: skip k. The old best.
d(k−1)[i][k]
d-k-minus-one of i, k option two, first half: the best way from i to the new stop k.
d(k−1)[k][j]
d-k-minus-one of k, j option two, second half: the best way from k on to j.
In plain words

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.

With numbers

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.

Follow one cell

Pick a cell. The staircase shows its value at every k. Drag k to read the two options at that step.

4

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.

At k = 3, Floyd-Warshall tests the route i → … → 3 → … → j. Which vertices may be stops inside the two halves?

Chapter 5

Loop Order and One Table

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.

Swap the loops

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.

Why can Floyd-Warshall overwrite its one table during layer k?

Chapter 6

Path Recovery

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.

Say it aloud

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.

π(k)[i][j]
pi-k of i, j the vertex just before j on the best route from i, with stops 1 to k allowed.
π(k−1)[k][j]
pi-k-minus-one of k, j the vertex just before j on the best route from k. The new route ends with that same road.
d[i][k] + d[k][j] < d[i][j]
the route through k is cheaper the test of Chapter 4: d[i][k] + d[k][j] beats d[i][j].
π(k−1)[i][j]
pi-k-minus-one of i, j otherwise keep the old pointer.
In plain words

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.

With numbers

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.

Walk the pointers back

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.

The route i to j improves through k. What goes into π[i][j]?

Chapter 7

Transitive Closure: Can I Get There?

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].

Say it aloud

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.

t(k)[i][j]
t-k of i, j 1 if i reaches j using stops 1 to k only, else 0.
t(k−1)[i][j]
t-k-minus-one of i, j i already reached j without k.
∨
or 1 if either side is 1. It plays the role of min.
t(k−1)[i][k]
t-k-minus-one of i, k i reaches the new stop k.
∧
and 1 only if both sides are 1. It plays the role of plus.
t(k−1)[k][j]
t-k-minus-one of k, j k reaches j.
In plain words

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.

With numbers

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.

Fill the reachability table

Drag k through A to E. Blue cells are 1. Purple cells turned to 1 at this step.

none

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.

What is t(0)[i][j], the start of the closure loops?

Chapter 8

Johnson's Algorithm

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.

Say it aloud

w-hat of u, v equals w of u, v, plus h of u, minus h of v.

ŵ(u, v)
w-hat of u, v the new cost of the road from u to v. Dijkstra runs on these.
w(u, v)
w of u, v the original road cost, which can be negative.
h(u)
h of u the potential of the start: the cheapest cost from a new vertex s to u.
h(v)
h of v the potential of the end.
In plain words

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).

With numbers

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.

Say it aloud

w-hat of p equals w of p, plus h of v-zero, minus h of v-q.

ŵ(p)
w-hat of p the new cost of the whole path p.
w(p)
w of p its original cost.
h(v0)
h of v-zero the potential of the first vertex.
h(vq)
h of v-q the potential of the last vertex.
In plain words

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).

With numbers

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.

Run Johnson's five steps

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.

Why does the shift w(u, v) + h(u) − h(v) keep the cheapest route the cheapest?

Chapter 9

Negative Cycles

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.

Say it aloud

A negative cycle exists if and only if there is some i with d of i, i less than zero.

negative cycle
a negative cycle a loop of roads with total cost below 0.
⇔
if and only if each side implies the other.
some i
some i at least one vertex; every vertex on the loop qualifies.
d[i][i] < 0
d of i, i less than zero the diagonal cell of i, after Floyd-Warshall, is negative.
In plain words

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.

With numbers

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.

Push one road below the edge

Drag the cost of road 4 → 3. The loop 2 → 4 → 3 → 2 sums to 5 plus that cost. Watch the diagonal.

−5

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.

After Floyd-Warshall, d[3][3] = −4 and d[5][5] = 0. What follows?

Chapter 10

The Field Guide

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.

Which algorithm

PlanTimeNegative roads?Use it when
Dijkstra from every vertexO(V2 log V + VE), Fibonacci heapNoevery road costs 0 or more
Bellman-Ford from every vertexO(V2E)Yesrarely: Johnson does the same job faster
Repeated squaringΘ(V3 log V)Yesyou study the min-plus algebra
Floyd-WarshallΘ(V3)Yesthe graph is dense or small; ten lines of code
JohnsonO(V2 log V + VE), Fibonacci heapYesthe graph is sparse and has negative roads

Terms and numbers

TermMeaningNumber on this page
W, D, Πdirect roads in; cheapest costs and predecessors outD[1][3] = −1, D[3][1] = 7
Min-plus productsum becomes min, times becomes plusL(3)[1][3] = −1
Repeated squaringL(2m) = L(m) ⊗ L(m)10 products for n = 1,000, not 998
Floyd-Warshall layer kstops 1 to k allowed9 cells drop at k = 4, none at k = 5
Predecessor updateπ[i][j] = π[k][j]5 → 4 → 3 → 2, cost 5
Transitive closureOR and AND in place of min and plus18 ones of 25
Potential hBellman-Ford costs from a new source sh = 0, −1, −5, 0, 0
Reweightingw + h(u) − h(v), never negativeroad 4 → 3: −5 becomes 0
Negative cyclesome d[i][i] < 0road 4 → 3 at −6: loop costs −1

Before you ship an all-pairs table

  1. Fill W with ∞, then 0 on the diagonal, then the roads. Keep only the cheapest of parallel roads.
  2. Put k in the outer loop.
  3. On an improvement, set π[i][j] = π[k][j].
  4. Scan the diagonal for a value below 0 before you trust or print anything.
  5. Pick Johnson for a sparse graph, Floyd-Warshall for a dense or small one.
  6. Check one row against a single-source run when you change the code.

The core code

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)

Where it sits

Keep going

The takeaway. Do not grow the route. Grow the set of allowed stops, one vertex per layer, and every cell needs just one comparison per layer.
A dense graph has 800 vertices, about 600,000 roads, and some negative roads but no negative cycle. Which plan fits best?

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.

Source

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).

CLRS Chapter 25 · All-Pairs Shortest Paths
Next: Maximum Flow · Back to Gleams