Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Floyd-Warshall proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Compute all-pairs distances by adding one allowed intermediate vertex at a time. Define zero diagonals and unreachable entries, keep the intermediate loop outermost, and distinguish finite shortest paths from negative-cycle evidence.
1 practice exercise1 interview problem
Recognize it when Many source-target queries share a small or dense weighted graph.
Checking your account…
Floyd-Warshall maintains a distance matrix for every source-target pair. Initialize zero diagonals, direct edge weights, and unreachable sentinels.
At layer k, each pair may either avoid vertex k or travel source to k plus k to target. Both subpaths use only earlier allowed intermediates.
def floyd_layers(matrix):
distance=[row.copy() for row in matrix];trace=[];n=len(matrix)
for middle in range(n):
previous=[row.copy() for row in distance]
for source in range(n):
for target in range(n):
if previous[source][middle] is not None and previous[middle][target] is not None:
candidate=previous[source][middle]+previous[middle][target]
if distance[source][target] is None or candidate<distance[source][target]:distance[source][target]=candidate
trace.append([row.copy() for row in distance])
return traceImplement floyd_layers(matrix). None means unreachable; return the distance matrix after each allowed intermediate vertex. The matrix is square with zero diagonal and no negative cycles; entries are direct costs or None.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def floyd_layers(matrix):
distance=[row.copy() for row in matrix];trace=[];n=len(matrix)
for middle in range(n):
previous=[row.copy() for row in distance]
for source in range(n):
for target in range(n):
if previous[source][middle] is not None and previous[middle][target] is not None:
candidate=previous[source][middle]+previous[middle][target]
if distance[source][target] is None or candidate<distance[source][target]:distance[source][target]=candidate
trace.append([row.copy() for row in distance])
return tracePredict all three matrices from the existing layer Lab. Only middle 1 introduces a new path; the unchanged layers still matter because each represents a larger allowed intermediate set.
| Step | Executed statement | State | Why |
|---|---|---|---|
| Allow 0 | previous=[row.copy() for row in distance] |
first layer unchanged |
No missing pair gains two reachable subpaths through vertex 0. |
| Allow 1 | candidate=previous[source][middle]+previous[middle][target] |
source=0,target=2,candidate=3+2=5 |
Both component paths already exist without needing vertex 1 internally. |
| Improve pair | distance[source][target]=candidate |
distance[0][2]=5 |
The formerly absent pair gains a real path through the new middle. |
| Allow 2 | trace.append([row.copy() for row in distance]) |
third layer unchanged |
Vertex 2 has no outgoing route to improve another pair. |
| Output | |
|---|---|
print(floyd_layers([[0, 3, None], [None, 0, 2], [None, None, 0]])) |
[[[0, 3, None], [None, 0, 2], [None, None, 0]], [[0, 3, 5], [None, 0, 2], [None, None, 0]], [[0, 3, 5], [None, 0, 2], [None, None, 0]]] |
A next-hop matrix is needed for actual route reconstruction. The distance matrix alone answers costs; reading a negative diagonal is a cycle warning rather than a valid finite shortest self-distance.
Only add the two subpaths when both are reachable. With explicit None sentinels this guard prevents invalid arithmetic from creating fake paths.
def all_pairs_distances(matrix):
distance=[row.copy() for row in matrix];n=len(matrix)
for middle in range(n):
for source in range(n):
for target in range(n):
if distance[source][middle] is not None and distance[middle][target] is not None:
candidate=distance[source][middle]+distance[middle][target]
if distance[source][target] is None or candidate<distance[source][target]:distance[source][target]=candidate
return distanceImplement all_pairs_distances(matrix). None means unreachable; return shortest distances after all intermediates. The matrix is square with zero diagonal and no negative cycles; entries are direct costs or None.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def all_pairs_distances(matrix):
distance=[row.copy() for row in matrix];n=len(matrix)
for middle in range(n):
for source in range(n):
for target in range(n):
if distance[source][middle] is not None and distance[middle][target] is not None:
candidate=distance[source][middle]+distance[middle][target]
if distance[source][target] is None or candidate<distance[source][target]:distance[source][target]=candidate
return distanceAfter all layers, a negative distance from a vertex to itself reveals a reachable negative cycle for that component. Path reconstruction needs a next-hop or predecessor matrix updated with distances.
Say: “After layer k, distance[i][j] is optimal using only intermediates through k. The recurrence either skips k or joins two earlier subpaths through it.” State O(V cubed) time and O(V squared) space.
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Floyd-Warshall proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| All-pairs recurrence | O(V^3) | O(V^3) | Three nested vertex loops; matrix initialization/copy is O(V^2). |
O(V^2) working matrix; the layer-trace Lab retains O(V^3) snapshot cells.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
A cost of zero is a reachable path, but bool(0) is False. Truthiness loses valid zero-weight subpaths.
Prevent it: Keep None for absence and guard both subpaths.
reachable = bool(distance)reachable = distance is not NoneWhere you will hit this: Compute All-Pairs Shortest Paths(opens in a new tab)
[[None]*2]*2 shares rows; changing one source distance changes another row too.
Prevent it: Allocate each row independently.
distance = [[None] * 2] * 2distance = [[None] * 2 for _ in range(2)]Where you will hit this: Compute All-Pairs Shortest Paths(opens in a new tab)
A None segment cannot be joined with a reachable segment by numeric addition.
Prevent it: Require both parts to be present before constructing a candidate.
candidate = first + secondcandidate = None if first is None or second is None else first + secondWhere you will hit this: Lowest Common Ancestor in a BST(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27