Bellman-Ford Algorithm
Dijkstra is fast but has one hard rule: no negative edge weights. Some real problems break that rule — currency exchange arbitrage, network cost models, or graphs where certain edges represent savings. That's where Bellman-Ford comes in.
Bellman-Ford finds the shortest path from one source node to all others, even when some edges have negative costs. It also detects a dangerous situation: a negative cycle — a loop whose total weight is negative. Going around it forever keeps lowering your cost, making the shortest path undefined.
The algorithm
Key insight: the shortest simple path in a graph with V nodes uses at most V-1 edges (any more and you revisit a node, creating a cycle). So: relax every edge, exactly V-1 times. After k passes, all shortest paths using at most k edges are finalized.
← → arrow keys to step · click elements to interact
Bellman-Ford Algorithm
Negative cycle detection
After V-1 passes all true shortest paths are finalized. If a V-th pass can still reduce a distance, some path is getting shorter because it loops through a negative cycle. Bellman-Ford catches this and reports it.
Bellman-Ford vs Dijkstra
- Dijkstra: \(O((V+E)\) log V), requires non-negative weights, fast in practice
- Bellman-Ford: \(O(VE)\), handles negative weights, detects negative cycles
Use Dijkstra when all weights are non-negative. Use Bellman-Ford when you have negative weights or need to detect negative cycles.
When does Bellman-Ford appear in practice?
- Currency arbitrage detection (negative cycle = free money loop)
- Network routing protocols (RIP uses Bellman-Ford)
- Problems where edge weights represent relative gains/losses