Every pair, one shared table.
Expand the set of allowed intermediate vertices with a precise loop order.
01 Model the idea
Floyd–Warshall computes shortest distances for every vertex pair using a matrix. At stage k, it considers whether travelling through vertex k improves each i→j route. The outermost loop must be the allowed intermediate vertex for the standard dynamic-programming invariant. Negative edges are allowed; a negative diagonal after completion indicates a negative cycle.
After stage k, optimal routes may use only the intermediates allowed so far.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
FOR each allowed intermediate k
FOR each source i and destination j
prefer the direct known route or route through k03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
infinity = float("inf")
distance = [[0, 4, 10], [infinity, 0, 2], [infinity, infinity, 0]]
for k in range(len(distance)):
for i in range(len(distance)):
for j in range(len(distance)):
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
print(distance[0][2])
print(any(distance[i][i] < 0 for i in range(len(distance))))6 False
- 1
Zero on the diagonal represents the empty path. Infinity distinguishes absent edges from legal zero-cost connections.
- 2
The route 0→1→2 costs six and improves the direct cost ten. A predecessor or next-hop matrix is needed if the caller wants routes rather than only distances.
- 3
Dense all-pairs work costs cubic time and quadratic storage. Repeated sparse single-source algorithms may be a better choice depending on graph size, density, and weight assumptions.
04 Count the cost
O(V³)
O(V²) distance matrix
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Run the recurrence on a two-edge path and verify the triangle inequality for the improved pair.
Reveal one possible solution +
inf = float("inf")
d = [[0, 3, inf], [inf, 0, 5], [inf, inf, 0]]
for k in range(3):
for i in range(3):
for j in range(3): d[i][j] = min(d[i][j], d[i][k] + d[k][j])
assert d[0][2] == 8
print(d[0][2])06 Check your reasoning
Which loop is outermost in the standard recurrence?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.