Sub topic 7
Detecting Negative Cycles with One More Pass
This chapter assumes you already know the basic Bellman-Ford loop, which relaxes every edge V-1 times. It also assumes the previous chapter's argument: when no negative cycle exists, every shortest path has at most V-1 edges, so V-1 rounds are enough. Here we use that guarantee in reverse. If the distances are still changing after V-1 rounds, something is wrong with the graph, and the only possible cause is a negative cycle.
The Idea: A Converged Graph Cannot Relax
After V-1 rounds on a graph with no reachable negative cycle, every dist[v] equals the true shortest distance. True shortest distances satisfy the triangle inequality on every edge:
- For every edge (u, v, w):
dist[v] <= dist[u] + w.
So a V-th pass over the edges finds nothing to relax. If the V-th pass does relax an edge, the distances have not converged, and they never will. That is the whole detection test: one more pass, looking for any edge where dist[u] + w < dist[v].
Why a Negative Cycle Always Triggers the Check
The other direction needs a short proof. Suppose a negative cycle v0 → v1 → … → vk = v0 is reachable from the source. Then every vertex on the cycle has a finite dist value after V-1 rounds. Assume, for contradiction, that no edge on the cycle can be relaxed. Then for each edge (v(i-1), v(i)) with weight w(i):
dist[v(i)] <= dist[v(i-1)] + w(i)
Sum these k inequalities. Each dist[v(i)] appears once on the left and once on the right, because the path is a cycle, so those terms cancel. What remains is:
0 <= w(1) + w(2) + … + w(k)
That says the cycle's total weight is non-negative, which contradicts the assumption that it is negative. So at least one edge on the cycle can still be relaxed, and the extra pass will find it.
The Detection Flow
The tutorial's main bellman_ford function follows this flow exactly and raises ValueError on detection. Raising an exception is the bluntest response, though, and real problems often need more: the cycle itself, or the set of vertices whose distance is actually undefined. The rest of this chapter covers both.
Detecting Cycles Anywhere in the Graph
To find negative cycles in any part of the graph, not just the part reachable from one source, add a virtual source with a weight-0 edge to every vertex. You don't have to build that vertex. Initializing every dist to 0 gives the same state you would have after the virtual source's first round. The augmented graph has n+1 vertices, so it needs n rounds in total. One of those is already done, which leaves n-1 real rounds plus one detection pass, n passes in all.
Recovering the Cycle Itself
Knowing that a cycle exists is often not enough. In arbitrage detection, for example, you need the actual sequence of trades. The predecessor array gives you the cycle:
- Remember any vertex
xthat was relaxed during the final pass. - Follow
predback n times fromx. A walk of n steps through n vertices must repeat a vertex, so you end up somewhere on a cycle in the predecessor graph. Any cycle in the predecessor graph is a negative cycle. - From that vertex, keep following
preduntil you return to it, and collect the vertices along the way.
def find_negative_cycle(n, edges):
# dist all 0 acts like a virtual source with 0-weight edges to every vertex
dist = [0] * n
pred = [None] * n
last = None
for _ in range(n):
last = None
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
last = v
if last is None:
return [] # converged: no negative cycle anywhere
# last was relaxed in the n-th pass; step back n times to land on the cycle
v = last
for _ in range(n):
v = pred[v]
cycle = [v]
u = pred[v]
while u != v:
cycle.append(u)
u = pred[u]
cycle.append(v)
cycle.reverse()
return cycle
edges = [(0, 1, 1), (1, 2, -1), (2, 1, -1), (2, 3, 2)]
print(find_negative_cycle(4, edges)) # [1, 2, 1]The cycle 1 → 2 → 1 has weight -2. Vertex 3 was the last vertex relaxed in the final pass, but it is not on the cycle. It sits downstream of the cycle. Without step 2, the code would have tried to trace a "cycle" starting at a vertex that has none.
Which Distances Are Actually Undefined?
A negative cycle does not ruin every distance. It ruins exactly the vertices reachable from the cycle. For those vertices, you can loop around the cycle as many times as you like before continuing, so their distance is minus infinity. Every other vertex still has a well-defined shortest distance. Reporting -inf for the affected vertices and real numbers for the rest gives a far more useful answer than an exception.
To compute this, run the normal V-1 rounds, then run further passes. In those passes, any edge that still relaxes sets its target to -inf. Python's float arithmetic spreads the value for you, because -inf + w is -inf, which is smaller than any finite value. V more passes are enough for the -inf marks to reach every affected vertex.
import math
def distances_with_neg_inf(n, edges, source):
dist = [math.inf] * n
dist[source] = 0
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
# Anything that still improves is affected by a negative cycle
for _ in range(n):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = -math.inf
return dist
edges = [(0, 1, 1), (1, 2, -1), (2, 1, -1), (2, 3, 2), (0, 4, 3)]
print(distances_with_neg_inf(5, edges, 0)) # [0, -inf, -inf, -inf, 3]Vertex 4 is reachable from the source but not from the cycle, so it keeps its true distance of 3.
Common Errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Using a large integer like `10**18` as infinity | An unreachable `u` with a negative edge gives `10**18 - 5 < 10**18`, which is a false relaxation and can produce a false "cycle" | Skip edges where `dist[u]` is the sentinel, or use `math.inf` |
| Treating an undirected negative edge as two directed edges | The pair u → v → u is itself a negative cycle | Bellman-Ford does not handle undirected graphs with negative edges; such a graph always contains a negative cycle |
| Running detection after an early exit | Wasted work, though not wrong | If a round changed nothing, the graph has converged and has no reachable negative cycle |
| Comparing floats exactly (for example, log-weighted exchange rates) | Rounding error makes a cycle with total weight -1e-16 look negative | Relax only when `dist[u] + w < dist[v] - eps` |
| Expecting the source-based check to find every cycle | Cycles the source cannot reach go unreported | Initialize all distances to 0 (the virtual source) |
Cost
The extra pass costs O(E), so detection keeps Bellman-Ford's total at O(V·E). The -inf spreading phase adds another O(V·E), and cycle recovery adds O(V). None of these change the asymptotic cost.
Exercise
In the graph with edges (0,1,2), (2,3,-4), (3,2,1), run the source-based extra-pass check from source 0. Does it report a negative cycle? Explain why, and say what change makes it detect the cycle.
Show answer
No. The cycle 2 → 3 → 2 has weight -3, but vertices 2 and 3 are unreachable from 0. Their distances stay at inf, inf + w is still inf, and no edge relaxes in the extra pass. Initializing every distance to 0, as findnegativecycle does, simulates a virtual source connected to all vertices, and then the cycle is detected.
Exercise
Summing the inequalities dist[v(i)] <= dist[v(i-1)] + w(i) around a cycle gives 0 <= total weight. Why do the dist terms cancel, and which assumption makes the sum valid?
Show answer
Each vertex on the cycle appears exactly once as a target (left side) and once as a source (right side), so the dist sums on both sides are equal and cancel. The sum is valid only if every dist on the cycle is finite. With inf values the subtraction is undefined, which is why the cycle must be reachable from the source.
Exercise
In findnegativecycle, why step back through pred exactly n times before tracing the cycle, rather than tracing from last directly?
Show answer
last may lie downstream of the cycle rather than on it. A walk of n predecessor steps passes through n+1 vertices in a graph with only n vertices, so it must repeat one. That means the walk has entered a cycle in the predecessor graph, and any vertex reached after n steps is on that cycle. Tracing from that vertex is guaranteed to return to it.