Sub topic 12
Reading Negative Cycles from the Diagonal
This chapter assumes you have seen the Floyd-Warshall recurrence and its triple loop over k, i, and j. It also assumes you know what a negative cycle is and why it makes shortest paths undefined. Here you will learn how one finished distance matrix tells you whether the graph has a negative cycle, and which entries of that matrix you can still trust.
Why the diagonal is the signal
Floyd-Warshall starts with dist[i][i] = 0 for every vertex. The value dist[i][i] is the shortest known walk from i back to itself. Without negative cycles, the best such walk is to stay put, so the value stays 0.
Suppose i lies on a cycle of total weight -2. Let k be the highest-numbered vertex on that cycle other than i. When the outer loop reaches k, both halves of the cycle (from i to k, and from k back to i) use only lower-numbered intermediates. The algorithm has already found both halves, or something even cheaper. The update dist[i][k] + dist[k][i] then drives dist[i][i] below zero. This gives the rule:
- The graph contains a negative cycle if and only if some
dist[i][i] < 0after the algorithm finishes. - Every vertex on a negative cycle ends with a negative diagonal entry.
Unlike Bellman-Ford's check, this test does not depend on a source vertex. It finds every negative cycle in the graph, wherever it sits.
A worked example
Vertex 0 can reach the cycle, and vertex 3 can be reached from it. A negative diagonal tells you only that a cycle exists. It does not tell you which pairs it damages. The pair (i, j) has no shortest path when some vertex k with dist[k][k] < 0 is reachable from i and can reach j. Those pairs have true distance negative infinity.
import math
def floyd_warshall(n, edges):
dist = [[math.inf] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for u, v, w in edges:
dist[u][v] = min(dist[u][v], w)
for k in range(n):
for i in range(n):
if dist[i][k] == math.inf:
continue
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 dist
def undefined_pairs(dist):
n = len(dist)
on_neg_cycle = [k for k in range(n) if dist[k][k] < 0]
bad = []
for i in range(n):
for j in range(n):
if any(dist[i][k] < math.inf and dist[k][j] < math.inf
for k in on_neg_cycle):
bad.append((i, j))
return on_neg_cycle, bad
edges = [(0, 1, 1), (1, 2, 1), (2, 1, -3), (2, 3, 2)]
dist = floyd_warshall(4, edges)
cycle_vertices, bad = undefined_pairs(dist)
print(cycle_vertices) # [1, 2]
print(bad) # [(0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]Pairs such as (0, 0) and (3, 3) keep correct values because no walk between them touches the cycle. Reachability survives a negative cycle: an entry is finite exactly when a path exists. That is why the marking step can trust the < math.inf tests.
Common errors
| Mistake | Consequence |
|---|---|
| Checking only `dist[0][0]` or one source row | Misses cycles that vertex 0 cannot reach |
| Treating every entry as wrong once a cycle appears | Throws away pairs that are still correct |
| Calling the path rebuilder on a pair marked undefined | The next-hop walk can loop forever |
| Initializing with `dist[u][v] = w` and ignoring self-loops | A negative self-loop `(v, v, -1)` gets overwritten by the diagonal 0, or the reverse, depending on order |
Exercise
You add the edge (3, 3, -1), a self-loop on vertex 3, to the example. Which diagonal entries end negative, and does the pair (0, 0) become undefined?
Show answer
Vertices 1, 2, and 3 end with negative diagonals, because the self-loop is itself a negative cycle and initialization sets dist[3][3] = min(0, -1) = -1. The pair (0, 0) stays defined: no walk from 0 back to 0 exists that passes through vertex 1, 2, or 3, since nothing returns to vertex 0.
Exercise
Why can't you detect the undefined pairs simply by checking which entries changed during a second run of the k loop?
Show answer
A second run detects pairs whose values still decrease, but the decrease spreads to new pairs only gradually. Some affected pairs might not change in that particular pass. The reachability test through a vertex with a negative diagonal marks every affected pair in a single O(V^3) pass.