Skip to contentKEEP THE CRAFTTHE SANCTUARY

Floyd-Warshall

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 Code Labs

Store All Pair Distances

Floyd-Warshall maintains a distance matrix for every source-target pair. Initialize zero diagonals, direct edge weights, and unreachable sentinels.

Add Intermediate Vertices One at a Time

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.

Trace Floyd-Warshall Layers

Reference
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 trace
Practice

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

Public tests

  • Add one intermediate set per layer

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Floyd-Warshall Layers

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 trace

A New Intermediate Connects a Previously Missing Pair

Predict 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.
Print 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.

Protect Unreachable Sums

Only add the two subpaths when both are reachable. With explicit None sentinels this guard prevents invalid arithmetic from creating fake paths.

Compute All-Pairs Distances

Reference
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 distance
Practice

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

Public tests

  • Relax through every allowed middle

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compute All-Pairs Distances

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 distance

Detect Negative Cycles on the Diagonal

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

Explain It in an Interview

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 Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
All-pairs recurrenceO(V^3)O(V^3)Three nested vertex loops; matrix initialization/copy is O(V^2).

Space

O(V^2) working matrix; the layer-trace Lab retains O(V^3) snapshot cells.

Assumptions

  • The trace freezes a previous matrix per layer; the final Lab uses an in-place standard recurrence.
  • A negative diagonal detects a negative cycle, but these Labs do not mark every affected pair as unbounded.

Invariants Worth Saying Aloud

  1. After layer k, each entry uses only intermediate vertices from 0 through k.
  2. Every update either retains an earlier path or joins two reachable subpaths through k.
  3. The empty path gives a zero diagonal when no negative cycle improves it.

When To Use Or Avoid Floyd-Warshall

Use It When

  • Use the intermediate-vertex recurrence when O(V^3) work is affordable.
  • Negative edges are allowed when there is no negative cycle affecting the requested finite paths.

Choose Another Tool When

  • For sparse single-source queries, use a suitable BFS/Dijkstra/Bellman-Ford method.
  • Do not present finite matrix entries as shortest-walk costs for pairs affected by a negative cycle.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Treating a reachable zero cost as absent

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.

Avoid

reachable = bool(distance)

Use instead

reachable = distance is not None

Aliasing rows in a distance matrix

[[None]*2]*2 shares rows; changing one source distance changes another row too.

Prevent it: Allocate each row independently.

Avoid

distance = [[None] * 2] * 2

Use instead

distance = [[None] * 2 for _ in range(2)]

Adding an unreachable subpath

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.

Avoid

candidate = first + second

Use instead

candidate = None if first is None or second is None else first + second

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.