Bellman-Ford and Negative Cycles
The Bellman-Ford algorithm solves the single-source shortest-path problem in its most general form: edge weights may be negative, and if a negative cycle is reachable from the source, the algorithm says so instead of returning wrong numbers. Its method is blunt: relax every edge, and repeat that times. It is slower than Dijkstra's algorithm, instead of , but it is the one to use when weights can be negative, it is the engine inside difference constraints and Johnson's algorithm, and its distributed form, the distance-vector protocol, routed the early Internet. The DSA course introduces it by example.
The algorithm
BELLMAN-FORD(G, w, s)
1 INITIALIZE-SINGLE-SOURCE(G, s)
2 for i = 1 to |V| - 1
3 for each edge (u, v) in G.E // in a fixed order
4 RELAX(u, v, w)
5 for each edge (u, v) in G.E
6 if v.d > u.d + w(u, v)
7 return FALSE // a negative cycle is reachable from s
8 return TRUEA common improvement stops as soon as a whole pass changes nothing: no later pass could change anything either.
Watching it work
The edges are listed, and relaxed, in an unlucky order: from the far end of the graph back toward the source. Each pass therefore extends the correct distances by only about one edge.
The Python version relaxes the edges in the same order and prints the same steps: every successful relaxation, the end of each pass, and the final check.
INF = float("inf")
def bellman_ford(V, edges, s):
d = {v: INF for v in V}
pi = {v: None for v in V}
d[s] = 0
for i in range(1, len(V)):
changed = False
for u, v, w in edges:
if d[u] != INF and d[u] + w < d[v]:
print(f"pass {i}: relax {u}->{v}: {d[u]} + {w} = {d[u] + w} < {d[v]}")
d[v], pi[v] = d[u] + w, u
changed = True
if not changed:
print(f"pass {i}: no change, stop early")
break
for u, v, w in edges:
if d[u] != INF and d[u] + w < d[v]:
return None, f"edge {u}->{v} can still be relaxed: negative cycle"
return d, pi
edges = [("E", "F", 2), ("D", "F", 5), ("D", "E", -3), ("C", "D", 4), ("B", "D", 7),
("B", "C", -1), ("A", "C", 6), ("A", "B", 5), ("A", "E", 10)]
d, pi = bellman_ford("ABCDEF", edges, "A")
print("distances:", d)
print("parents: ", pi)pass 1: relax A->C: 0 + 6 = 6 < inf
pass 1: relax A->B: 0 + 5 = 5 < inf
pass 1: relax A->E: 0 + 10 = 10 < inf
pass 2: relax E->F: 10 + 2 = 12 < inf
pass 2: relax C->D: 6 + 4 = 10 < inf
pass 2: relax B->C: 5 + -1 = 4 < 6
pass 3: relax D->E: 10 + -3 = 7 < 10
pass 3: relax C->D: 4 + 4 = 8 < 10
pass 4: relax E->F: 7 + 2 = 9 < 12
pass 4: relax D->E: 8 + -3 = 5 < 7
pass 5: relax E->F: 5 + 2 = 7 < 9
distances: {'A': 0, 'B': 5, 'C': 4, 'D': 8, 'E': 5, 'F': 7}
parents: {'A': None, 'B': 'A', 'C': 'B', 'D': 'C', 'E': 'D', 'F': 'E'}
Pass 1 only reaches the neighbours of , because the edges leaving , and were relaxed before those vertices had estimates. Each later pass pushes the correct values one edge further. The shortest path to is (weight ), which has edges, the most a simple path can have, and its edges are listed back to front, so all five passes are needed and the early stop never triggers. With the edges listed source-first, one pass would have done all the work.
Why it works
Theorem. If has no negative cycle reachable from , then after the passes for every vertex, and BELLMAN-FORD returns TRUE. If a negative cycle is reachable from , it returns FALSE.
Proof
No negative cycle. Let be reachable from . By the previous lessons it has a simple shortest path with . Pass relaxes every edge, in particular , so the path's edges are relaxed in order: the first in pass 1, the second in pass 2, and so on. By the path-relaxation property, after pass . Unreachable vertices keep (no-path property). At the end, the triangle inequality gives for every edge, so the check on lines 5 to 7 passes.
A negative cycle. Let be a reachable cycle with . Suppose, for contradiction, that the algorithm returns TRUE, so for . All these estimates are finite (the cycle is reachable, and after passes every reachable vertex has a finite estimate). Summing around the cycle:
Both sums of estimates contain every vertex of the cycle exactly once, since , so they cancel, leaving , a contradiction.
Running time. Initialization is , the passes and the check : in total with adjacency lists (or with the early stop). The practice problem Shortest Paths with Negative Edges asks for exactly this algorithm.
Finding the negative cycle
The check only says that a cycle exists. To show it, take an edge that can still be relaxed and relax it, which sets . Then follow predecessors back from for steps. That is enough to be sure of standing on a cycle of the predecessor graph; walking on until a vertex repeats prints it, and every cycle of the predecessor graph has negative weight.
INF = float("inf")
def negative_cycle(V, edges, s):
d = {v: INF for v in V}
pi = {v: None for v in V}
d[s] = 0
for _ in range(len(V) - 1):
for u, v, w in edges:
if d[u] != INF and d[u] + w < d[v]:
d[v], pi[v] = d[u] + w, u
for u, v, w in edges:
if d[u] != INF and d[u] + w < d[v]:
pi[v] = u # relax it once more
x = v
for _ in range(len(V)): # now x is on a cycle of predecessors
x = pi[x]
cycle, y = [x], pi[x]
while y != x:
cycle.append(y)
y = pi[y]
cycle.reverse()
weight = sum(w2 for a, b, w2 in edges for i in range(len(cycle))
if a == cycle[i] and b == cycle[(i + 1) % len(cycle)])
return cycle, weight
return None, 0
edges = [("A", "B", 1), ("B", "C", 2), ("C", "D", -4), ("D", "B", 1), ("C", "E", 3)]
cycle, weight = negative_cycle("ABCDE", edges, "A")
print("negative cycle:", " -> ".join(cycle + [cycle[0]]), "weight", weight)negative cycle: B -> C -> D -> B weight -1
Arbitrage. Currency exchange is the classic application. If one unit of currency buys units of , a sequence of trades gains money exactly when the product of its rates exceeds 1. Taking turns products into sums and "greater than 1" into "negative": an arbitrage opportunity is a negative cycle.
import math
rates = {("EUR", "USD"): 1.10, ("USD", "JPY"): 150.0, ("JPY", "EUR"): 0.0062,
("USD", "GBP"): 0.79, ("GBP", "EUR"): 1.16, ("EUR", "GBP"): 0.85, ("JPY", "GBP"): 0.0052}
V = sorted({c for pair in rates for c in pair})
edges = [(a, b, -math.log(r)) for (a, b), r in rates.items()]
d = {v: 0.0 for v in V} # start from every currency at once
pi = {v: None for v in V}
for _ in range(len(V) - 1):
for a, b, w in edges:
if d[a] + w < d[b] - 1e-12:
d[b], pi[b] = d[a] + w, a
bad = next(((a, b) for a, b, w in edges if d[a] + w < d[b] - 1e-12), None)
if bad:
a, b = bad
pi[b] = a
x = b
for _ in range(len(V)):
x = pi[x]
cycle, y = [x], pi[x]
while y != x:
cycle.append(y); y = pi[y]
cycle.reverse()
product = math.prod(rates[(cycle[i], cycle[(i + 1) % len(cycle)])] for i in range(len(cycle)))
print("arbitrage:", " -> ".join(cycle + [cycle[0]]), f"turns 1 unit into {product:.4f}")
else:
print("no arbitrage")arbitrage: USD -> JPY -> EUR -> USD turns 1 unit into 1.0230
Starting every currency at 0 is the same as adding a new source with a 0-weight edge to every vertex, a trick that reappears in difference constraints and Johnson's algorithm. It finds negative cycles anywhere in the graph, not only those reachable from one source.
In C++
The C++ version uses long long distances and a large sentinel for , and stops early when a pass changes nothing.
#include <cstdio>
#include <vector>
struct Edge { int u, v, w; };
int main() {
const int n = 6; // A..F
std::vector<Edge> edges = {{4,5,2}, {3,5,5}, {3,4,-3}, {2,3,4}, {1,3,7}, {1,2,-1}, {0,2,6}, {0,1,5}, {0,4,10}};
const long long INF = 1LL << 60;
std::vector<long long> d(n, INF);
d[0] = 0;
int passes = 0;
for (int i = 1; i < n; ++i) {
bool changed = false;
for (const auto& e : edges)
if (d[e.u] != INF && d[e.u] + e.w < d[e.v]) { d[e.v] = d[e.u] + e.w; changed = true; }
++passes;
if (!changed) break;
}
bool negative = false;
for (const auto& e : edges)
if (d[e.u] != INF && d[e.u] + e.w < d[e.v]) negative = true;
std::printf("passes: %d, negative cycle: %s\n", passes, negative ? "yes" : "no");
for (int v = 0; v < n; ++v) std::printf("d(%c) = %lld\n", 'A' + v, d[v]);
}passes: 5, negative cycle: no
d(A) = 0
d(B) = 5
d(C) = 4
d(D) = 8
d(E) = 5
d(F) = 7
Test yourself
Why does Bellman-Ford run exactly passes?
- Because each pass fixes one vertex
- Because, without negative cycles, some shortest path to each vertex has at most edges, and pass fixes the -th edge of it
- Because a tree has edges
- To detect negative cycles
What is the running time of Bellman-Ford with adjacency lists?
After passes, an edge still satisfies . What does this prove?
- The edge has negative weight
- A negative-weight cycle is reachable from
- The graph is disconnected
- is unreachable
To detect arbitrage among currencies with exchange rates , which edge weights turn the problem into negative-cycle detection?