Sub topic 7
Detecting Negative Cycles with One More Pass
This chapter assumes you know how Bellman-Ford relaxes every edge for V-1 rounds and why those rounds are enough when no negative cycle exists. Here we use that result to detect when a negative cycle exists.
The idea
The previous chapter showed that without a reachable negative cycle, every shortest path uses at most V-1 edges. After V-1 rounds, every distance is therefore final. If one more pass over the edges still finds an edge (u, v, w) with dist[u] + w < dist[v], the distances were not final. The only way that can happen is a negative cycle reachable from the source.
Why the check cannot miss a cycle
Suppose a cycle v0 → v1 → … → vk = v0 is reachable from the source and has total weight below zero. Assume the final pass finds nothing to relax. Then for every edge on the cycle, dist[v_i] <= dist[v_{i-1}] + w(v_{i-1}, v_i). Adding these inequalities around the cycle makes each dist term appear once on each side, so they cancel and leave 0 <= total cycle weight. That contradicts the cycle being negative. So at least one edge on the cycle must still relax.
The distances in this argument are finite because the cycle is reachable. This is why the check sees only cycles reachable from the source.
Finding the cycle itself
Often you need the cycle and not just a yes-or-no answer. For example, an arbitrage detector has to report the trades. If edge (u, v) relaxes in the extra pass, then v either sits on a negative cycle or is downstream of one. Following pred back n times is guaranteed to land on a vertex inside the cycle. From there, keep walking until you return to that vertex.
import math
def find_negative_cycle(n, edges, source):
dist = [math.inf] * n
pred = [None] * 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
pred[v] = u
for u, v, w in edges:
if dist[u] + w < dist[v]:
pred[v] = u
x = v
for _ in range(n): # step back n times to land on the cycle
x = pred[x]
cycle = [x]
y = pred[x]
while y != x:
cycle.append(y)
y = pred[y]
cycle.reverse()
return cycle
return None
edges = [(0, 1, 1), (1, 2, -1), (2, 3, -1), (3, 1, 1)]
print(find_negative_cycle(4, edges, 0)) # [1, 2, 3]The cycle 1 → 2 → 3 → 1 has weight -1 + -1 + 1 = -1.
Common errors
- Using a bare check instead of the full pass. Checking only the edges that changed in round V-1 can miss a cycle. Check every edge.
- Stopping at the first relaxed vertex. The vertex
vmay lie downstream of the cycle and not on it. Walk back n steps first. - Expecting global detection. A negative cycle that the source cannot reach is never found. To detect a negative cycle anywhere in the graph, add a new vertex with a 0-weight edge to every other vertex and run from it. You can also start every
distat 0. - Mixing
infwith integers in other languages. In Python,math.inf + wstaysinf. With integer sentinels such asINT_MAX, skipuwhendist[u]is the sentinel, or the addition overflows.
Exercise
Remove the edge (3, 1, 1) and add (3, 1, 3) to the example graph. Does findnegativecycle return a cycle? Explain using the cycle's weight.
Show answer
No, it returns None. The cycle 1 → 2 → 3 → 1 now weighs -1 + -1 + 3 = 1. That is not negative, so after 3 rounds the distances are final and no edge relaxes in the extra pass.
Exercise
A graph has vertices 0..4. A negative cycle runs through vertices 3 and 4, and the only edges into that pair come from vertex 2, which source 0 cannot reach. What does the extra pass report, and how would you change the call to detect the cycle?
Show answer
It reports no cycle, because dist[3] and dist[4] stay infinite and their edges never relax. Add a new vertex 5 with a 0-weight edge to every vertex, then run the algorithm from vertex 5 with n = 6.