🗺️ Bellman-Ford Algorithm — Shortest Paths with Negative Weights
Watch Bellman-Ford relax every edge V−1 times to find shortest paths from a source, even with negative weights, then run one more pass to detect negative cycles.
About Bellman-Ford Algorithm
The Bellman-Ford algorithm, developed independently by Richard Bellman (1958) and Lester Ford Jr. (1956), computes shortest paths from a single source vertex to every other vertex in a weighted directed graph. Unlike Dijkstra's algorithm, it tolerates negative edge weights, making it essential for applications such as currency arbitrage detection and network routing protocols like RIP. Bellman-Ford is a dynamic programming algorithm: it repeatedly relaxes every edge — replacing dist[v] with dist[u] + w(u,v) whenever that sum is smaller — for exactly V−1 passes, since the longest possible simple shortest path visits at most V−1 edges. A final, extra pass checks whether any distance can still improve; if so, the graph contains a negative-weight cycle reachable from the source, meaning no shortest path is well-defined. This gives Bellman-Ford O(V·E) time and O(V) space complexity, slower than Dijkstra's O((V+E) log V) but strictly more general.
Frequently Asked Questions
Why does Bellman-Ford need V−1 passes?
Because the longest possible shortest path in a graph with V vertices (one that doesn't repeat a vertex) can have at most V−1 edges. Each full pass over every edge guarantees that at least one more edge along every shortest path becomes finalized, so after V−1 passes all shortest distances have fully propagated.
How does Bellman-Ford detect negative cycles?
After the required V−1 passes, the algorithm runs one extra pass over all edges. If any edge can still be relaxed — meaning a distance would still decrease — a negative-weight cycle reachable from the source must exist, since a valid shortest-path tree would already be stable by that point.
How does Bellman-Ford compare to Dijkstra's algorithm?
Both compute single-source shortest paths, but Dijkstra uses a greedy priority queue and requires non-negative weights, running in O((V+E) log V). Bellman-Ford relaxes every edge on every pass, tolerates negative weights, and can detect negative cycles, at the cost of a slower O(V·E) running time.
Can Bellman-Ford handle undirected graphs with negative edges?
No. Any undirected edge with a negative weight is equivalent to a two-vertex negative cycle (u→v and v→u), so Bellman-Ford would immediately flag it as a negative cycle. The algorithm is designed for directed graphs; negative weights only make consistent sense once edges have a direction.
Watch Bellman-Ford relax every edge V−1 times to find shortest paths from a source, even with negative weights, then run one more pass to detect negative cycles.
2D · HTML5 Canvas 2D · 60 FPS target · runs fully client-side, no install