TExcelTAD
Home › Graph Algorithms › Bellman-Ford and Negative Cycles

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 V−1V - 1 times. It is slower than Dijkstra's algorithm, Θ(VE)\Theta(VE) instead of O(Elg⁡V)O(E \lg V), 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

text
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 TRUE

A 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.

python · try it yourself
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 AA, because the edges leaving BB, CC and EE were relaxed before those vertices had estimates. Each later pass pushes the correct values one edge further. The shortest path to FF is A→B→C→D→E→FA \to B \to C \to D \to E \to F (weight 5−1+4−3+2=75 - 1 + 4 - 3 + 2 = 7), which has V−1=5V - 1 = 5 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 GG has no negative cycle reachable from ss, then after the V−1V - 1 passes v.d=δ(s,v)v.d = \delta(s, v) for every vertex, and BELLMAN-FORD returns TRUE. If a negative cycle is reachable from ss, it returns FALSE.

Proof

No negative cycle. Let vv be reachable from ss. By the previous lessons it has a simple shortest path ⟨v0=s,v1,…,vk=v⟩\langle v_0 = s, v_1, \ldots, v_k = v \rangle with k≤V−1k \le V - 1. Pass ii relaxes every edge, in particular (vi−1,vi)(v_{i-1}, v_i), 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, v.d=δ(s,v)v.d = \delta(s, v) after pass kk. Unreachable vertices keep ∞\infty (no-path property). At the end, the triangle inequality gives v.d=δ(s,v)≤δ(s,u)+w(u,v)=u.d+w(u,v)v.d = \delta(s, v) \le \delta(s, u) + w(u, v) = u.d + w(u, v) for every edge, so the check on lines 5 to 7 passes.

A negative cycle. Let c=⟨v0,v1,…,vk=v0⟩c = \langle v_0, v_1, \ldots, v_k = v_0 \rangle be a reachable cycle with ∑i=1kw(vi−1,vi)<0\sum_{i=1}^{k} w(v_{i-1}, v_i) < 0. Suppose, for contradiction, that the algorithm returns TRUE, so vi.d≤vi−1.d+w(vi−1,vi)v_i.d \le v_{i-1}.d + w(v_{i-1}, v_i) for i=1,…,ki = 1, \ldots, k. All these estimates are finite (the cycle is reachable, and after V−1V - 1 passes every reachable vertex has a finite estimate). Summing around the cycle:

∑i=1kvi.d≤∑i=1kvi−1.d+∑i=1kw(vi−1,vi)\sum_{i=1}^{k} v_i.d \le \sum_{i=1}^{k} v_{i-1}.d + \sum_{i=1}^{k} w(v_{i-1}, v_i)

Both sums of estimates contain every vertex of the cycle exactly once, since v0=vkv_0 = v_k, so they cancel, leaving 0≤∑w(vi−1,vi)0 \le \sum w(v_{i-1}, v_i), a contradiction.

Running time. Initialization is Θ(V)\Theta(V), the passes Θ(VE)\Theta(VE) and the check Θ(E)\Theta(E): Θ(VE)\Theta(VE) in total with adjacency lists (or O(VE)O(VE) 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 (u,v)(u, v) that can still be relaxed and relax it, which sets v.π=uv.\pi = u. Then follow predecessors back from vv for VV 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.

python · try it yourself
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 aa buys rabr_{ab} units of bb, a sequence of trades gains money exactly when the product of its rates exceeds 1. Taking w(a,b)=−ln⁡rabw(a, b) = -\ln r_{ab} turns products into sums and "greater than 1" into "negative": an arbitrage opportunity is a negative cycle.

python · try it yourself
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 ∞\infty, and stops early when a pass changes nothing.

cpp · try it yourself
#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 V−1V - 1 passes?

  1. Because each pass fixes one vertex
  2. Because, without negative cycles, some shortest path to each vertex has at most V−1V - 1 edges, and pass ii fixes the ii-th edge of it
  3. Because a tree has V−1V - 1 edges
  4. To detect negative cycles

What is the running time of Bellman-Ford with adjacency lists?

  1. O(Elg⁡V)O(E \lg V)
  2. Θ(VE)\Theta(VE)
  3. Θ(V+E)\Theta(V + E)
  4. Θ(V3)\Theta(V^3)

After V−1V - 1 passes, an edge (u,v)(u, v) still satisfies v.d>u.d+w(u,v)v.d > u.d + w(u, v). What does this prove?

  1. The edge has negative weight
  2. A negative-weight cycle is reachable from ss
  3. The graph is disconnected
  4. vv is unreachable

To detect arbitrage among currencies with exchange rates rabr_{ab}, which edge weights turn the problem into negative-cycle detection?

  1. w(a,b)=rabw(a, b) = r_{ab}
  2. w(a,b)=−rabw(a, b) = -r_{ab}
  3. w(a,b)=−ln⁡rabw(a, b) = -\ln r_{ab}
  4. w(a,b)=1/rabw(a, b) = 1 / r_{ab}