Bellman-Ford & SPFA
Imagine a price board at a currency exchange. Each row shows the current cost to get from one city to another. Every morning you check: "Can any route go cheaper if I re-route through a different city?" You keep updating the board until no more improvements are possible.
That's Bellman-Ford. Unlike Dijkstra, it doesn't assume all prices are positive — it handles negative edge weights and can even detect the pathological case where prices spiral to negative infinity (a negative cycle).
The Algorithm: V−1 Rounds of Relaxation
Initialize: dist[source] = 0, all other distances = ∞. Then repeat V−1 times:
For every edge (u, v, w) in the graph, check: if dist[u] + w < dist[v], update dist[v] = dist[u] + w.
Why V−1 rounds? Any simple path in a V-vertex graph has at most V−1 edges. Each round of relaxation can "activate" one more edge of the shortest path. After V−1 rounds, all simple shortest paths are fully computed — as long as no negative cycle exists.
Detecting Negative Cycles
After the V−1 rounds, run one more round. If any distance still decreases, a negative cycle is reachable from the source. Why? In a graph without negative cycles, shortest paths are simple paths — V−1 rounds already found them. Any further improvement means the algorithm is looping around a negative cycle, shaving off cost with each lap.
Negative cycles make shortest paths undefined: you can make the total cost arbitrarily negative by going around the cycle more times. Bellman-Ford is the standard algorithm to detect this condition.
SPFA (Shortest Path Faster Algorithm)
Bellman-Ford wastes time in each round relaxing edges from vertices whose distances haven't changed. SPFA fixes this with a queue: only enqueue vertices whose distances were just improved, and only relax their outgoing edges.
In practice, SPFA runs in \(O(kE)\) where k ≈ 2 on typical graphs — much faster than Bellman-Ford's \(O(VE)\). But adversarial inputs can make it degenerate back to \(O(VE)\), so for competitive programming it's treated with caution. For negative cycle detection, SPFA tracks how many times each vertex is enqueued — if any vertex is enqueued V times, a negative cycle exists.
Classic Application: Currency Arbitrage
Represent currencies as vertices, exchange rates as directed edges with weight −log(rate). A negative cycle in this graph means multiplying the exchange rates around the cycle gives a product greater than 1 — a profitable arbitrage loop. Bellman-Ford detects exactly this.