Skip to the workspace
Pebellslearn by building
Shortest Paths at Scale  ›  Lesson

All-Pairs Shortest Paths

All-Pairs Shortest Paths 30 minLet one more depot act as a stopover, n times over

dsa / All-Pairs Shortest Paths

Explore each scene at your own pace.

01 · Growing the set of allowed stopovers

Growing the set of allowed stopovers

All-Pairs Shortest Paths

Definition
The Floyd-Warshall algorithm computes the shortest distance between every pair of nodes at once. It allows each node in turn as a possible stopover and updates a distance table whenever going through it is shorter, in O(n³) time.
In plain words
It is a full table of travel times between every pair of towns. You ask, one town at a time, whether going through that town is quicker than the route you already have, and update the whole table whenever it is.

In short: Floyd–Warshall fills a full n × n table of cheapest costs between every pair of stops in three nested loops. The outer loop allows one more stop, k, as a possible stopover; each cell then takes the smaller of its current cost or the route through k: dist[i][k] + dist[k][j]. After all n stops have been allowed as stopovers, every entry is final. It costs O(n³) time and O(n²) space — worth it exactly when you need every pair, not just one.

Three nodes i, k, j: a dashed grey direct edge from i to j labelled dist[i][j] old, and two solid green edges i-to-k and k-to-j, with the formula dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

Meridian's dispatch desk quotes prices all day: what does it cost to move a pallet from the mill to the harbour? Then the quay to the depot, then the harbour to the mill. Running a search for every quote is wasteful when the network barely changes between morning and night. Better to build one table overnight, every depot to every depot, and turn each quote into a lookup.

That table is the all-pairs shortest paths problem. You could run a search from each depot in turn, but there is a simpler algorithm that fills the whole table at once, handles rebates, and is three nested loops long: Floyd–Warshall.

Growing the set of allowed stopovers

Number the depots 0 to n − 1. Start with a table holding only direct roads: the road's cost where there is one, 0 on the diagonal, infinity elsewhere. Think of that as "the cheapest route with no stopovers allowed".

Now allow depot 0 as a stopover. For each pair (i, j), the best route either avoids depot 0 (the table has it already) or goes i → 0 → j, costing dist[i][0] + dist[0][j]. Take the smaller. Then allow depot 1, then 2, and so on. Once all n are allowed, the table is complete.

Written as a recurrence, with k the newest allowed stopover:

dk[i][j]=min⁡(dk−1[i][j],  dk−1[i][k]+dk−1[k][j])d_k[i][j] = \min\big(d_{k-1}[i][j],\; d_{k-1}[i][k] + d_{k-1}[k][j]\big)

That is dynamic programming again, and the table is the DP table. The whole algorithm is n snapshots of one matrix. Scrub through them for Meridian's four depots. At each stopover, the highlighted row and column are the only cells the pass reads, and the arrows show which two cells each improvement came from:

watch it move · grid

Floyd–Warshall is n snapshots of one table. Each pass allows one more depot as a stopover, and reads only that depot's row and column.

Stopover depot. Row i, column j is the cheapest cost from i to j. The pass for the depot reads only the depot's row (costs from it) and its column (costs to it). 4 by 4 table. 16 of 16 cells filled.

1 / 7

The quay → mill route (quay → harbour → depot → mill) was only found in the last pass, because it reused harbour → mill from the first. Each pass builds on the finished work of the ones before.

A pass only has to look at row k and column k to decide everything:

What does this print?
inf = float("inf")
dist = [[0, 3, 8, inf], [3, 0, 2, inf], [inf, inf, 0, 1], [4, inf, inf, 0]]
k = 0                                     # allow only the depot as a stopover
for i in range(4):
    for j in range(4):
        if dist[i][k] + dist[k][j] < dist[i][j]:
            dist[i][j] = dist[i][k] + dist[k][j]
print(dist[3][1], dist[3][2])
Scene 1 of 11
Project context and further resources
You're building a piece ofMeridian — the router
This piece — depot_matrix(): Builds every depot-to-depot cost overnight, so each quote is a lookup.
Scenario Dispatch quotes prices between depots thousands of times a day. Rather than search the network for every quote, Meridian builds one depot-to-depot cost table overnight, and every quote becomes a lookup.
depot_matrix.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
depot_matrix(depots, roads) → listEvery depot-to-depot cheapest cost as a matrix, None where unreachable.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.