Sub topic 23
Bellman-Ford and negative cycle detection
This chapter assumes you know edge relaxation from the previous chapter, Dijkstra's algorithm, and Big-O notation. Dijkstra fails when an edge weight is negative. Bellman-Ford handles negative edges. It also reports when a negative cycle makes shortest paths undefined.
The idea
A shortest path with no repeated vertex has at most V - 1 edges. Bellman-Ford exploits this. It relaxes every edge, and it repeats that pass V - 1 times.
After pass k, dist[v] is at most the weight of the shortest path to v that uses at most k edges. Take a shortest path s → v1 → ... → v with at most V - 1 edges. Its first edge is relaxed correctly in pass 1, its second in pass 2, and so on. This holds in any edge order, and extra relaxations never hurt.
Negative cycles
A negative cycle is a cycle whose weights sum to less than zero. If you can reach one from the source, going around it again lowers the distance without limit. Shortest distances to every vertex reachable from the cycle are then undefined (minus infinity).
If there is no such cycle, V - 1 passes finish the job. So one extra pass detects the problem. If any edge can still be relaxed in pass V, a negative cycle is reachable from the source.
INF = float('inf')
def bellman_ford(n, edges, source):
dist = [INF] * n
dist[source] = 0
for _ in range(n - 1):
changed = False
for u, v, w in edges:
if dist[u] != INF and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
break
for u, v, w in edges:
if dist[u] != INF and dist[u] + w < dist[v]:
return None # negative cycle reachable from source
return dist
print(bellman_ford(4, [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 2)], 0)) # [0, 4, 1, 3]
print(bellman_ford(3, [(0, 1, 1), (1, 2, -3), (2, 1, 1)], 0)) # NoneIn the second graph, the cycle 1 → 2 → 1 weighs -3 + 1 = -2, so distances keep falling. The check pass finds an edge that can still be relaxed and returns None.
Complexity
Each pass scans E edges, and there are at most V - 1 passes, so the time is O(VE). The space is O(V) for the distance array, plus the edge list. Dijkstra with a binary heap runs in O((V + E) log V), so use Bellman-Ford only when negative edges are possible.
| Property | Dijkstra | Bellman-Ford |
|---|---|---|
| Negative edges | Fails | Works |
| Negative cycle detection | No | Yes |
| Time | O((V + E) log V) | O(VE) |
| Approach | Greedy | Repeated relaxation (DP over edge count) |
Common errors
- Skipping the
dist[u] != INFguard. In Python,inf + wstays infinite, so the code still works. In C with integerINT_MAX, adding a negative weight gives a wrong value, and adding a positive weight overflows. - Missing unreachable cycles. A cycle that the source cannot reach never relaxes, because its vertices keep infinite distance. To detect any negative cycle in the whole graph, start every
distat 0 instead. - Treating an undirected edge as one edge. An undirected edge with negative weight is a two-edge cycle with negative total weight. Bellman-Ford then reports a negative cycle.
- Assuming exactly V - 1 passes always run. The early exit is safe. If a full pass changes nothing, no later pass will.
- Believing that dist after pass V - 1 is correct when a negative cycle exists. It is not. Always run the check pass before trusting the values.
Recovering a negative cycle
To print the cycle, store parent[v] whenever you relax. If an edge (u, v) relaxes in the check pass, then v is on a negative cycle or is reachable from one. Follow parent from v for V steps. This lands you on the cycle itself, and you can then walk it until you return to the starting vertex.
Exercise
A directed graph has 6 vertices and 9 edges. What is the maximum number of edge relaxation attempts Bellman-Ford makes, including the negative cycle check, if the early exit is not used?
Show answer
The main loop runs V - 1 = 5 passes of 9 edges, which is 45 attempts. The check pass adds 9 more, for a total of 54.
Exercise
The edges are (A,B,2), (B,C,-5), (C,A,2), and the source is A. Does Bellman-Ford report a negative cycle? Justify your answer.
Show answer
Yes. The cycle A → B → C → A has weight 2 - 5 + 2 = -1, which is negative, and it is reachable from A. After 2 passes, one more pass still relaxes an edge, so the check pass returns a negative cycle.
Exercise
Why does Dijkstra's algorithm give a wrong answer on a graph with a negative edge but no negative cycle, while Bellman-Ford does not?
Show answer
Dijkstra settles a vertex permanently once it is the closest unsettled one, assuming no later path can be shorter. A negative edge can make a later path shorter, so the settled value can be wrong. Bellman-Ford never settles early. It relaxes all edges repeatedly, so a better path found later still updates the distance.