Three problems that need the distance between every pair of vertices. The move: build the whole table once with Floyd-Warshall, then answer thresholds, new links and visit-all questions from it.
You work on a service mesh, a shard cluster and a warehouse. The three problems on this street ask about the shortest distance between many pairs, and not from one source. One search per question would repeat the same work.
The shared plan is to build the table of all pairs once, and then read it. The questions differ only in how they read it.
| Problem | The table is read to | What the answer needs |
|---|---|---|
| City with the fewest neighbours within a threshold | count each row against a budget | the row counts, and the larger id on a tie |
| All pairs shortest distances | add up the table after each new link | an update of the table for each link |
| Minimum cost to travel every pair | find the best order of visits | the distances between the picks, then a bitmask |
Exercise · Predict the output: Routes through stops. The links are two-way. This code builds all pairs with k as the outer loop. What does it print for the distance from hub 0 to hub 3?
links = [[0, 1, 4], [1, 2, 1], [2, 3, 1], [0, 3, 9], [0, 2, 6]]
n = 4
dist = [[99] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for a, b, ms in links:
dist[a][b] = dist[b][a] = ms
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
print(dist[0][3])Before you code, ask what the answer reads from the table. A count per row, a changed table, or a smaller table all start from the same build.
After the loop for k, dist[i][j] holds the shortest route from i to j that uses only vertices 0 to k as stops. After the last k, every pair is final.
The loop over k must be the outer one. Inside it, every pair asks one question: is the route through k shorter than the best one so far? The answer uses only rows and columns that earlier values of k have already made correct.
Then read the table. A threshold problem counts the entries of a row that are at most the budget, and skips the diagonal. A visit-all problem keeps only the rows and columns of the places to visit. A problem with arriving links updates the table, as the next section shows.
The build costs n cubed steps. For 100 vertices that is 1,000,000, whatever the links are.
Floyd-Warshall allows each vertex in turn as a stop. The distance from 0 to 3 drops from 9 to 6 when stop 2 is allowed.
Exercise · Find the bug: Two links between the same pair. Services are joined by two-way links, and two links may join the same pair. This builds the table of all pairs. Which line is wrong?
def all_pairs(n, links):
dist = [[10**9] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for a, b, ms in links:
dist[a][b] = dist[b][a] = ms
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return distThe Academy lesson Dijkstra's shortest paths answers questions from one source. Bits and maths shows a bitmask as a set. This street does not teach them again. It changes three things.
One table replaces many searches. Dijkstra from every vertex of 100 vertices with 300 links makes 60,000 edge checks. With 4,000 links it makes 800,000. Floyd-Warshall always makes 1,000,000 steps, but it is shorter to write, and it gives the table that the questions need.
A new link updates the table, not rebuilds it. A shortest route uses a new link at most once. So for every pair, compare the old distance with the routes through the link, in both directions. For 300 vertices that is 90,000 steps per link, against 27,000,000 for a rebuild.
A visit-all question shrinks the table. With 12 picks, trying every order means 479,001,600 orders. A bitmask over the picks has 2^12 x 12 = 49,152 states. Going to the nearest pick first is not enough: on the warehouse example it costs 16, and the best order costs 13.
With the stop in the innermost loop, a route with two stops can be missed. Put the stop in the outer loop.
Exercise · Break it: The stop loop goes inside. This builds all pairs, but its loops run over i, then j, then k. Find an input where the table is wrong.
def all_pairs(n, links):
dist = [[10**9] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for a, b, ms in links:
dist[a][b] = min(dist[a][b], ms)
dist[b][a] = min(dist[b][a], ms)
for i in range(n):
for j in range(n):
for k in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return distSolve them in this order. The first reads the table, the second keeps it up to date, and the third shrinks it.
Before you code each problem, write two lines: what the table holds, and how the answer reads it. If the second line is a loop over every pair, check whether one table is enough.
Give each problem about 25 minutes. Spend the first four on the two lines, and say them aloud as you would to an interviewer. Then write the size of the table and the cost of building it.
Three edge cases return on every rung. A pair with no route needs a sentinel, so add it with care. Two links may join the same pair, so keep the smaller. A vertex has distance 0 to itself, and it is not its own neighbour.
When a solution fails, check the loop order before the body. Most wrong answers on this street come from k in the wrong loop, or from a table that was updated with a plain assignment.
Checkpoint · All pairs and thresholds
Q1/5 What does Floyd-Warshall guarantee after the loop for vertex k?
Answer: B
The pass for k allows k as a stop. After the last k every vertex is allowed, so every pair is final.
Q2/5 Which loop must be the outer loop of Floyd-Warshall?
Answer: C
Each pass for k builds on the passes before it. With k inside, a route with two stops can be missed.
Q3/5 A new link arrives in a graph of 300 vertices. What is the cost of updating the table of all pairs?
Answer: B
A shortest route uses the new link at most once, so every pair needs only to compare two routes through it. That is 300 squared steps.
Q4/5 Two services are at distance 0 from themselves. When you count the peers of a service within a budget, what do you do with the diagonal?
Answer: B
The problem defines a peer as another service. Counting the diagonal adds 1 to every row.
Q5/5 Why does the visit-all problem use a bitmask over the picks?
Answer: B
With 12 picks there are 479,001,600 orders but only 49,152 states of the form (set visited, last pick).
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.