Sub topic 4
Negative Cycles: When Shortest Paths Stop Existing
This chapter assumes you know how weighted directed graphs are stored as edge lists or adjacency lists, and that you can read short Python programs. It builds on the earlier chapter's definition of the single-source and all-pairs shortest path problems. Edge relaxation and Bellman-Ford come later, so nothing here depends on them.
Negative edge weights are fine on their own. A graph can contain many of them and still have well-defined shortest paths. The real trouble is a negative cycle, which is a directed cycle whose edge weights add up to less than zero. Before you write any algorithm that allows negative weights, you need to know what its answer should be when such a cycle exists.
What a negative cycle does to "shortest"
A walk is a sequence of vertices joined by edges, and it may repeat vertices. Suppose a walk from s to t passes through a cycle of total weight c < 0. Adding one more lap around that cycle produces another valid walk from s to t, and its cost is lower by |c|. A second lap lowers it again. No walk is the cheapest, because there is always a cheaper one. The infimum of the walk costs is negative infinity, and there is no minimum.
So when we say "the shortest path from s to t is undefined", we mean that no finite minimum exists. By convention, algorithms report the distance as -inf.
A concrete graph
The walk 0 → 1 → 2 → 3 → 4 costs 1 + 2 − 4 + 2 = 1. Each extra lap around 1 → 2 → 3 → 1 subtracts 1. The program below confirms this.
edges = [(0, 1, 1), (1, 2, 2), (2, 3, -4), (3, 1, 1),
(3, 4, 2), (0, 6, 3), (5, 1, 7)]
weights = {(u, v): w for u, v, w in edges}
def walk_cost(walk):
return sum(weights[(u, v)] for u, v in zip(walk, walk[1:]))
for laps in range(4):
walk = [0] + [1, 2, 3] * (laps + 1) + [4]
print(laps, walk_cost(walk))
# 0 1
# 1 0
# 2 -1
# 3 -2Reachability decides who is affected
A negative cycle does not ruin every distance in the graph. A vertex t gets distance -inf from source s only when both of these hold:
- Some vertex on the cycle is reachable from
s. tis reachable from some vertex on the cycle.
If the cycle cannot be reached from s, your walks never enter it. If t cannot be reached from the cycle, the extra laps never lead to t. In the graph above:
| Vertex | Reachable from 0? | Reachable from the cycle? | Distance from 0 |
|---|---|---|---|
| 0 | yes | no | 0 |
| 1, 2, 3 | yes | yes | `-inf` |
| 4 | yes | yes | `-inf` |
| 5 | no | no | `+inf` (unreachable) |
| 6 | yes | no | 3 |
Vertex 5 has an edge into the cycle, but that edge doesn't help it. Vertex 6 shares a source with the cycle yet still has an ordinary finite distance. This code computes the classification with two breadth-first searches:
from collections import deque
def reachable(n, edges, starts):
adj = [[] for _ in range(n)]
for u, v, _ in edges:
adj[u].append(v)
seen = set(starts)
queue = deque(starts)
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in seen:
seen.add(v)
queue.append(v)
return seen
def classify(n, edges, source, cycle_vertices):
from_source = reachable(n, edges, [source])
if any(c in from_source for c in cycle_vertices):
poisoned = reachable(n, edges, list(cycle_vertices))
else:
poisoned = set()
result = {}
for v in range(n):
if v not in from_source:
result[v] = "+inf"
elif v in poisoned:
result[v] = "-inf"
else:
result[v] = "finite"
return result
edges = [(0, 1, 1), (1, 2, 2), (2, 3, -4), (3, 1, 1),
(3, 4, 2), (0, 6, 3), (5, 1, 7)]
print(classify(7, edges, 0, [1, 2, 3]))
# {0: 'finite', 1: '-inf', 2: '-inf', 3: '-inf', 4: '-inf', 5: '+inf', 6: 'finite'}In this code the cycle's vertices are given. Finding them automatically is the job of the detection techniques covered in later chapters. Keep the two-condition rule in mind, though, because many implementations only report that a cycle exists and then treat every distance as invalid. That is more pessimistic than it needs to be.
Why not just forbid repeated vertices?
A natural fix is to redefine the problem: find the cheapest simple path, meaning a path that visits no vertex twice. A simple path in a finite graph has finitely many options, so a minimum always exists.
This problem is NP-hard when negative cycles are present. Give every edge weight -1. The cheapest simple path from s to t then becomes the longest simple path, and deciding whether a path of length V − 1 exists is the Hamiltonian path problem. Bellman-Ford and Floyd-Warshall are fast because they work with walks and depend on the fact that, without negative cycles, some shortest walk is already simple. When a negative cycle exists, that fact no longer holds, and so the efficient algorithms report the cycle instead of answering.
Edge cases that trip people up
Zero-weight cycles are harmless
A cycle of total weight exactly 0 doesn't reduce the cost when you go around it. Shortest distances stay finite, though there may be infinitely many shortest walks. Any algorithm that uses a strict < comparison will not loop forever on such a cycle.
A negative self-loop is a negative cycle
An edge (v, v, -2) is a cycle of length one. Code that skips self-loops when reading input will quietly miss it. In an adjacency matrix it shows up as a negative diagonal entry before the algorithm even runs.
Undirected graphs with any negative edge
An undirected edge {u, v} with weight -3 is usually modelled as two directed edges, u → v and v → u. Together those form a cycle of weight -6. Any undirected graph with a negative edge therefore contains a negative cycle under this model, and Bellman-Ford will report it. Undirected problems with negative weights need different techniques, such as matching-based methods, which this tutorial does not cover.
Multi-edges
If two edges both go from u to v, only the cheaper one matters for shortest paths. If you are checking a cycle by hand, use the minimum weight for each pair. The Floyd-Warshall code later in the tutorial does this with its if w < dist[u][v] check.
What a correct algorithm must report
When negative weights are allowed, a full answer for each target can take one of three values:
| Status | Meaning |
|---|---|
| finite `d` | A shortest path exists with cost `d` |
| `+inf` | No path from the source |
| `-inf` | Some walk passes through a reachable negative cycle |
Some library functions only raise an error when they find a negative cycle. Others return per-vertex -inf markers. Check which behavior you have before you rely on the distances it returns.
Exercise
In the chapter's graph, change the edge 2 → 3 from weight -4 to weight -3. What are the distances from vertex 0 to vertices 1, 4 and 6 now?
Show answer
The cycle 1 → 2 → 3 → 1 now weighs 2 − 3 + 1 = 0, which is not negative, so every distance is finite. dist(1) = 1, dist(4) = 1 + 2 − 3 + 2 = 2, and dist(6) = 3.
Exercise
Add the edge (4, 5, 1) to the original graph, keeping 2 → 3 at -4. Which vertices now have distance -inf from vertex 0, and does vertex 5's status change?
Show answer
Vertex 5 is now reachable from vertex 4, which is reachable from the cycle, and the cycle is reachable from 0. So vertex 5 changes from +inf to -inf. The full -inf set becomes {1, 2, 3, 4, 5}. Vertices 0 and 6 stay finite.
Exercise
A graph has a negative cycle among vertices 7, 8 and 9, and none of them is reachable from source 0. Should a shortest-path routine run from vertex 0 report a negative cycle?
Show answer
No. The cycle has no effect on any distance from vertex 0, so every distance from 0 is well defined. Reporting an error for the whole run would be overly pessimistic. Single-source detection with Bellman-Ford finds only cycles reachable from the source, which is the correct behavior here.