Sub topic 12
Reading Negative Cycles from the Diagonal
This chapter assumes you have already seen the Floyd-Warshall recurrence and its triple loop, the meaning of a negative cycle, and how Bellman-Ford detects one with an extra relaxation pass. Here we focus on one question: after Floyd-Warshall finishes, how do you know whether its answers can be trusted?
The answer comes from the diagonal of the distance matrix, the entries dist[i][i]. They start at 0, and a correct run on a graph without negative cycles leaves them at 0. If any of them ends up negative, the graph contains a negative cycle, and some of the other entries no longer mean anything.
What a Diagonal Entry Measures
Floyd-Warshall maintains this invariant: after processing intermediate vertices 0..k, dist[i][j] is at most the weight of every simple path from i to j whose intermediate vertices all lie in {0, ..., k}. Every value it stores is also the weight of some real walk in the graph, because each update adds two walk weights that were already stored.
Apply that to i == j. A "path" from i back to i is a closed walk. The cell starts at 0, which stands for the empty walk of staying put. It can only drop below 0 if the algorithm finds a closed walk through i with negative total weight.
So a diagonal entry answers this question: what is the cheapest way to leave i and come back? In a graph with no negative cycles every round trip costs at least 0, and the entry stays at 0.
Why Every Vertex on a Negative Cycle Gets Flagged
Take a simple negative cycle C and any vertex v on it. Walking around C from v back to v is a closed path whose intermediate vertices are the other vertices of C. By the final round, every vertex has been allowed as an intermediate, so the invariant gives:
dist[v][v] <= weight(C) < 0
A self-loop with negative weight is the one-vertex case. It is caught during initialization, because the edge loop in the code replaces the 0 with the smaller weight w.
The converse also holds. A negative dist[i][i] is the weight of a real closed walk through i, and any closed walk with negative weight contains a simple cycle with negative weight. So:
| Diagonal after the run | Conclusion |
|---|---|
| All entries are 0 | No negative cycle anywhere in the graph; every `dist[i][j]` is a true shortest distance |
| Some `dist[i][i] < 0` | A negative cycle exists, and `i` can both reach it and be reached from it |
A Worked Example
The graph below has a negative cycle 1 → 2 → 3 → 1 with weight 1 + (-4) + 2 = -1. Vertex 0 can reach the cycle but cannot be reached from it. Vertex 4 can be reached from the cycle but cannot reach it.
import math
def floyd_warshall(n, edges):
dist = [[math.inf] * n for _ in range(n)]
nxt = [[None] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
nxt[i][i] = i
for u, v, w in edges:
if w < dist[u][v]:
dist[u][v] = w
nxt[u][v] = v
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]
nxt[i][j] = nxt[i][k]
has_negative_cycle = any(dist[i][i] < 0 for i in range(n))
return dist, nxt, has_negative_cycle
edges = [(0, 1, 2), (1, 2, 1), (2, 3, -4), (3, 1, 2), (3, 4, 3)]
n = 5
dist, nxt, neg = floyd_warshall(n, edges)
print(neg) # True
print([i for i in range(n) if dist[i][i] < 0]) # [1, 2, 3]
print(dist[0][0], dist[4][4]) # 0 0Vertices 1, 2 and 3 are flagged because each lies on the cycle. Vertices 0 and 4 keep a diagonal of 0. Neither one has any closed walk through it, even though both are connected to the cycle.
Which Distances Become Undefined
Finding the cycle is half the job. The other half is working out which pairs (i, j) have no shortest path. The distance from i to j is minus infinity exactly when some vertex k with dist[k][k] < 0 is reachable from i and can reach j. You can loop around that cycle as many times as you like before continuing to j.
The finished matrix already holds the reachability information. A finite dist[i][k] means k is reachable from i. That gives a direct post-processing step:
def mark_undefined(dist):
n = len(dist)
bad = [k for k in range(n) if dist[k][k] < 0]
result = [row[:] for row in dist]
for i in range(n):
for j in range(n):
for k in bad:
if dist[i][k] < math.inf and dist[k][j] < math.inf:
result[i][j] = -math.inf
break
return result
final = mark_undefined(dist)
print(final[0]) # [0, -inf, -inf, -inf, -inf]
print(final[4]) # [inf, inf, inf, inf, -inf]... see note belowLook at row 4 more carefully. No vertex in bad is reachable from 4, so nothing in that row changes. The real output is [inf, inf, inf, inf, 0]. Vertex 0 is different. It reaches the cycle, so every vertex from 1 to 4 has distance minus infinity from 0, and 4 is one of them. This post-pass costs O(V² · B), where B is the number of flagged vertices, so it never exceeds the O(V³) of the main loop.
Gotchas
Path reconstruction can loop forever
When a negative cycle exists, the next-hop matrix may describe a route that circles the cycle forever. Calling fw_path on a pair marked minus infinity can then run without end. Check the diagonal, or use the marked matrix, before rebuilding any path.
The numbers can blow up
With a negative cycle present, each round can roughly double the size of the negative values, because later updates add together entries that are already negative. Over V rounds the magnitudes can grow exponentially. Python integers handle this without trouble, apart from slowing down. In languages with fixed-width integers the values can overflow and wrap around to large positive numbers, which hides the cycle. A common defense is to clamp values at some floor, or to stop as soon as a diagonal entry goes negative.
Fake infinity sentinels
Code in C++ or Java often uses a large number such as 10**9 in place of infinity. Then INF + (-4) is less than INF, and the algorithm "discovers" paths that don't exist. The if dist[i][k] == math.inf: continue guard handles the left operand. With a numeric sentinel you also need to skip the update when dist[k][j] is the sentinel.
Early exit is possible
If you only need a yes or no answer, check dist[i][i] < 0 after each outer k iteration, or after each (i, k) pair, and return as soon as one turns negative. This avoids the remaining work and the growing values.
Comparison with Bellman-Ford Detection
| Property | Bellman-Ford extra pass | Floyd-Warshall diagonal |
|---|---|---|
| What it finds | Negative cycles reachable from one source | Every negative cycle in the graph |
| Cost | O(V·E) | O(V³) |
| Identifies affected vertices | Needs extra work (follow predecessors V times) | Flagged vertices are read straight off the diagonal |
| Undefined pairs | Only for the chosen source | For all pairs, after the post-pass |
Bellman-Ford is silent about a negative cycle that its source cannot reach. Floyd-Warshall checks every vertex, so the diagonal test covers the whole graph.
Exercise
Add the edge (4, 0, 1) to the example graph and rerun floyd_warshall. Which vertices now have a negative diagonal entry, and why does vertex 0 get flagged even though it is not on the cycle 1 → 2 → 3 → 1?
Show answer
All five vertices, [0, 1, 2, 3, 4]. With the new edge, 0 → 1 → 2 → 3 → 4 → 0 is a closed walk, so 0 and 4 now share a strongly connected component with the negative cycle. A closed walk such as 0 → 1 → 2 → 3 → 1 → 2 → 3 → 4 → 0 goes around the cycle repeatedly before returning, and each extra lap lowers its weight by 1. Floyd-Warshall finds a negative closed walk through 0 and 4 this way, even though neither vertex lies on the cycle itself.
Exercise
A colleague's version of the code skips the edge initialization step for self-loops: it sets dist[i][i] = 0 after reading the edges, not before. What goes wrong on a graph whose only negative cycle is the self-loop (2, 2, -5)?
Show answer
Resetting dist[2][2] to 0 after loading the edges throws away the -5. No other closed walk through 2 uses the self-loop, because Floyd-Warshall only reaches it through the stored dist[2][2] entry. The diagonal stays at 0 and the cycle goes undetected. The fix is to set the diagonal to 0 first, then apply the edges with the "if w < dist[u][v]" check, so a negative self-loop replaces the 0.