Bellman-Ford Algorithm
Imagine a currency-trading network where each edge represents an exchange rate. This rate is expressed as a negative logarithm. That way, multiplying rates becomes adding weights. Some cycles in this network could represent arbitrage opportunities. These are sequences of trades that make money from nothing. Dijkstra's Algorithm cannot even be run safely on such a graph. It assumes every edge weight is nonnegative. It also greedily commits to shortest distances too early. We need an algorithm that tolerates negative weights. Ideally, it should also detect when the whole premise is broken by a negative cycle. The Bellman-Ford algorithm solves exactly this problem. It computes shortest paths from a single source in a weighted directed graph. This graph may contain negative edge weights. It also certifies whether a negative-weight cycle reachable from the source exists at all. Dijkstra trades away generality for speed. Bellman-Ford trades away some speed for robustness instead. It works on graphs Dijkstra cannot handle. This robustness comes at the cost of a slower running time. This algorithm sits at the heart of real infrastructure. The Routing Information Protocol (RIP) and other distance-vector routing protocols are essentially distributed, asynchronous versions of Bellman-Ford. In these protocols, routers repeatedly relax edges toward their neighbors. They continue until distances stabilize. Arbitrage detection in financial networks is one example application. Constraint systems solved via difference constraints are another. Certain layout and scheduling problems also apply here. All of these reduce to shortest paths with signed weights. This makes negative-cycle detection a first-class feature rather than an edge case. This article builds Bellman-Ford from the ground up. It covers the relaxation-based mechanism and why exactly rounds suffice. It also covers the extra pass that detects negative cycles. A full correctness proof via induction on path length is included. A worked trace shows distances evolve round by round. It closes by connecting the algorithm to the broader landscape of shortest-path methods it feeds into.
- Bellman-Ford computes single-source shortest paths in graphs with possibly negative edge weights.
- It performs passes of edge relaxation over all edges, then one extra pass to detect negative cycles.
- Correctness rests on the fact that a shortest simple path has at most edges.
- Running time is ; space is for distance and predecessor arrays.
- If any edge can still be relaxed after passes, a negative cycle is reachable from the source.
- It generalizes Dijkstra's setting and underpins distance-vector routing protocols and all-pairs algorithms.
Relax every edge in the graph exactly times — that is enough to propagate the true shortest distance along any simple path, and one more pass reveals whether a negative cycle is undermining the whole notion of "shortest."
The idea
A weighted directed graph with weight function may contain edges of negative weight. The single-source shortest-path problem asks, for a source vertex , for the minimum total weight of any path from to , for every . When all cycles reachable from have nonnegative total weight, this quantity is well defined for every vertex, and the shortest path can always be taken to be simple (no repeated vertices). But if some reachable cycle has negative total weight, an adversary can loop around it arbitrarily many times, driving the "shortest path" to . Detecting this situation is as important as computing distances. The mechanism relies on <a class="wiki-link" href="/wiki/cs-algo-edge-relaxation" data-track="wiki_article.body.wiki_link">Edge Relaxation and Optimal Substructure</a>: maintaining an estimate for every vertex, initialized to except , and repeatedly checking each edge with weight . If , the estimate is improved to , and is recorded as 's predecessor. Relaxation never sets a distance too low — it only tightens an upper bound toward the truth — and shortest-path problems exhibit optimal substructure: a shortest path's prefixes are themselves shortest paths. Bellman-Ford exploits this by relaxing every edge in the graph, in an arbitrary fixed order, and repeating the sweep enough times for the correct distances to propagate everywhere, however tangled the graph's structure.
How it works
The key structural fact is: if the graph has no negative-weight cycle reachable from , then every shortest path is simple and therefore has at most edges. A single sweep over all edges relaxes every edge once; after sweeps, every shortest path of at most edges has been correctly computed (this is proved rigorously below). So sweeps suffice to correctly compute for all vertices, provided no negative cycle interferes. A final -th pass checks for negative cycles: if any edge can still be relaxed, some shortest-path estimate has not stabilized, which is only possible if a negative cycle is reachable from . ``` BELLMAN-FORD(G, w, s): // Initialization for each vertex v in G.V: d[v] = INFINITY pred[v] = NIL d[s] = 0 // Main relaxation phase: V - 1 passes for i = 1 to |G.V| - 1: for each edge (u, v) in G.E: if d[u] != INFINITY and d[u] + w(u, v) < d[v]: d[v] = d[u] + w(u, v) pred[v] = u // Negative-cycle detection pass for each edge (u, v) in G.E: if d[u] != INFINITY and d[u] + w(u, v) < d[v]: return "NEGATIVE CYCLE REACHABLE FROM s" return (d, pred) ``` A practical optimization: if an entire pass over all edges performs no relaxation, the distances have already converged, and the algorithm can terminate early — no further pass will change anything, by the same inductive argument used for correctness. This does not improve the worst-case bound but often helps in practice on graphs where distances stabilize quickly. To reconstruct an actual shortest path to a vertex (when no negative cycle blocks it), follow the `pred` pointers backward from to ; this traces a shortest path in reverse, by the same logic used in other predecessor-based shortest-path methods.
Complexity & correctness
Time complexity. Initialization takes . The main phase runs passes, each of which relaxes every edge exactly once, costing per pass, for total. The detection pass adds one more sweep. Overall running time is
This is worst-case, best-case, and average-case identical in the standard formulation — the algorithm always performs the full passes regardless of input, unless the early-termination optimization is used, in which case the best case (distances converge in one pass, e.g. all edges from direct with no improving edges beyond) drops to , while the worst case remains . Space usage is for the distance array, predecessor array, and loop counters, plus the storage of the graph itself, which is not attributable to the algorithm's auxiliary space.
Correctness — the core lemma. Let denote the true shortest-path weight from to , defined as if a negative cycle on some path to exists, if is unreachable, and the ordinary minimum otherwise. Assume for now no negative cycle is reachable from . Define as the minimum weight of any path from to using at most edges. Claim: after the -th pass of the main loop, for every vertex , and in fact once equals the true shortest-path weight (which happens once reaches the number of edges in some shortest simple path to ). Proof by induction on . Base case : before any pass, and for (since for , as zero edges cannot reach any vertex but ). This holds as equality trivially. Inductive step: suppose after pass , for all (this stronger equality form holds by the same argument used for Edge Relaxation and Optimal Substructure applied repeatedly — relaxation never overestimates, and a straightforward induction shows it never underestimates either, so equality is maintained at each stage where the bound is tight). Consider any vertex and a shortest path using at most edges achieving . Let be the second-to-last vertex on , and its last edge. The prefix of up to uses at most edges and, by optimal substructure, is itself a shortest such path, so its weight is . By the inductive hypothesis, before pass begins. Since pass relaxes edge (every edge is relaxed in every pass), afterward
Combined with the invariant that relaxation never produces an estimate below the true shortest-path weight (a standard fact: is not quite what we want — rather one shows by induction that is always the weight of some actual path from to , hence can never be violated in the wrong direction), we obtain after pass . This closes the induction. Since no negative cycle is reachable from , every shortest path is simple and has at most edges, so for every vertex . By the lemma, after passes, exactly — the algorithm is correct.
Correctness of negative-cycle detection. If no negative cycle is reachable from , the argument above shows all have converged to after passes, and a further relaxation pass changes nothing — no edge can satisfy , since that would mean a path shorter than the true shortest path exists, a contradiction. So the detection pass correctly reports no negative cycle. Conversely, suppose a negative cycle is reachable from . Suppose for contradiction that after the detection pass, holds for every edge of (no relaxation triggers). Summing these inequalities around the entire cycle gives
The sums of on both sides are equal (they range over the same cyclic set of vertices), so they cancel, leaving
the total weight of the cycle. But is a negative cycle, so , a contradiction. Hence at least one edge of must still be relaxable, and the detection pass correctly flags the negative cycle. This is a proof by contradiction resting on summing telescoping inequalities around the cycle.
Tradeoffs. Bellman-Ford's running time is markedly worse than Dijkstra's (with a Fibonacci heap) or (with a binary heap) on graphs with nonnegative weights. The price of handling negative weights and detecting negative cycles is this quadratic-in-the-worst-case blowup on dense graphs ( gives ). Bellman-Ford should be reserved for graphs where negative weights are actually possible; when weights are guaranteed nonnegative, Dijkstra is strictly preferable.
Worked example
Consider a graph with source and vertices , with directed edges: (weight 6), (weight 7), (weight -2), (weight -4), (weight 8), (weight -3), (weight 3). Process edges in this fixed order every pass: , , , , , , . Initial: .
| Pass | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| init | — | — | — | — | — | — | — | ∞ | ∞ | ∞ | ∞ |
| 1 | relax: | relax: | relax: | , relax: | relax: | , relax: | 6→3 | 7→4 | ∞→1 | ∞→4 | |
| 2 | , relax: | , relax: | , relax: | 3→0 | 4 | 1→-2 | 4→1 | ||||
| 3 | , relax: | , relax: | , relax: | 0 | 4→-2 | -2→-5 | 1→-2 | ||||
| 4 | no change | , relax: | 0→-6 | -2 | -5 | -2 |
There are 4 vertices besides the source among , so and the main phase runs passes, exactly as tabulated. Notice the estimate for is still improving on pass 4 (), showing the need for the full passes rather than stopping early on appearance-only convergence. Now run the detection pass (pass 5) with the converged values :
- : . OK.
- : . OK.
- : . Relaxable!
Since edge can still be relaxed, the algorithm reports a negative cycle reachable from . Indeed, tracing gives total weight — exactly the negative cycle the proof by contradiction predicted, and the reason distances kept dropping () without ever stabilizing.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Running only passes total instead of plus a separate check | Confusing the relaxation phase with the detection phase | Use exactly relaxation passes, then one distinct detection pass |
| Treating as a number in relaxation | can wrap around or produce wrong comparisons in code with sentinel integers | Explicitly skip relaxation when is unreachable/infinite |
| Assuming Bellman-Ford gives finite distances even with a negative cycle | Distances to vertices reachable through the cycle are truly , not just "wrong" | Always run the detection pass; report unreachable-via-safe-path status explicitly |
| Applying Dijkstra-style early stopping (fixing a vertex once popped) | Habit from nonnegative-weight algorithms | Never mark vertices "done" in Bellman-Ford — any vertex's distance can improve until the very last relaxing pass |
| Off-by-one in loop bound (`i = 1 to V` instead of `V-1`) | Miscounting how many edges a shortest simple path can have | Recall a simple path visits at most vertices, hence at most edges |
| Ignoring edges not reachable from a negative cycle when reporting | Reporting "negative cycle" globally without checking reachability from | Only trust the detection pass's answer as "a negative cycle reachable from the source exists," not "anywhere in the graph" |
Pioneers & history
Origins · 1 minRichard E. Bellman and how this was discovered
Bellman developed the mathematical theory of dynamic programming in the 1950s, formalizing the principle of optimality — that an optimal policy's remaining decisions form an optimal policy for the remaining subproblem. This is the same optimal-substructure principle underlying shortest-path relaxation, and Bellman's 1958 paper "On a routing problem" laid out the recurrence that computes shortest paths by successively increasing the number of edges allowed, which is precisely the structure formalized above as .
Where this matters
Distance-vector routing protocols, most notably RIP, implement a distributed, asynchronous relative of Bellman-Ford: each router repeatedly exchanges distance estimates with neighbors and relaxes them, converging to shortest paths without any central authority computing the whole graph at once. This distributed structure is a direct descendant of the relaxation invariant proved above, adapted to a setting with no fixed pass order or global synchronization. Arbitrage detection in currency and commodities trading networks reduces to negative-cycle detection: taking the negative logarithm of exchange rates turns multiplicative profit into additive path weight, and a negative cycle corresponds exactly to a sequence of trades yielding guaranteed profit. Bellman-Ford is the standard tool for scanning such graphs. Systems solving difference constraints — systems of inequalities of the form , arising in scheduling, VLSI layout timing, and constraint-based type checking — are transformed into a graph where each constraint becomes a weighted edge, and Bellman-Ford both finds a feasible assignment and certifies infeasibility via a negative cycle. Bellman-Ford also serves as a building block for more advanced algorithms. It underlies Johnson's algorithm for all-pairs shortest paths, which reweights a graph's edges using Bellman-Ford's output to make all weights nonnegative, then runs Dijkstra from every vertex — a technique previewed by the broader landscape of All-Pairs Shortest Paths Overview. The relaxation idea itself, generalized to capacities and augmenting structures, resurfaces in flow-based methods such as the Ford-Fulkerson Method, where Bellman-Ford can be used to find augmenting paths with favorable termination guarantees (as in the Edmonds-Karp refinement).
:::quiz[What does it mean if, after V-1 passes, some edge (u, v) still satisfies d[u] + w(u,v) < d[v]?]
- The graph is disconnected
- The source vertex was chosen incorrectly
- A negative-weight cycle is reachable from the source ✓
- The algorithm needs to run Dijkstra instead
Ask the tutor: How does Johnson's algorithm use Bellman-Ford's output to reweight edges before running Dijkstra from every vertex?
Can Bellman-Ford handle undirected graphs with negative edges?
Not in general. Any undirected edge with a negative weight is equivalent to two opposite directed edges of that same negative weight between the same pair of vertices, which immediately forms a negative-weight cycle of length two (go across and come back). Bellman-Ford would correctly detect this as a negative cycle, but that means shortest paths are undefined the moment any undirected edge is negative. Bellman-Ford is therefore typically applied to directed graphs, or to undirected graphs where all weights are guaranteed nonnegative (in which case Dijkstra is usually preferable anyway).
Does Bellman-Ford still work if the graph has negative edges but no negative cycles?
Yes — this is precisely its intended use case. As long as no cycle reachable from the source has negative total weight, every shortest path remains simple and well-defined, and the correctness proof goes through exactly as shown, converging to true distances within V-1 passes. Negative edges alone are not a problem; only negative cycles reachable from the source break the notion of a shortest path. Bellman-Ford handles negative edges gracefully and only raises an alarm when a genuine negative cycle is present.
How does the choice of edge order within a pass affect the result?
It does not affect final correctness after V-1 full passes, but it can affect how quickly distances converge within those passes. If edges happen to be processed in an order aligned with a shortest path's vertex sequence, that path's distance can propagate in a single pass; in the worst adversarial order, it can take all V-1 passes for a single long path's information to fully propagate. The worst-case bound of O(VE) accounts for the least favorable ordering, so correctness proofs are stated to hold regardless of edge order.
Why is Bellman-Ford slower than Dijkstra, and when should each be used?
Bellman-Ford relaxes every edge in every one of V-1 passes without any way to skip work, giving O(VE). Dijkstra uses a priority queue to always relax edges from the vertex with the currently smallest tentative distance, finalizing distances one at a time and touching each edge only once overall, giving O(E + V log V) with a good heap. Dijkstra's speed comes from relying on nonnegative weights, which guarantees that once a vertex is popped from the queue its distance is final. Use Dijkstra whenever weights are guaranteed nonnegative; use Bellman-Ford when negative weights are possible or negative-cycle detection is required.
Can Bellman-Ford be parallelized or distributed?
Yes, and this is exactly what distance-vector routing protocols do. Each vertex (router) can independently relax its incoming or outgoing edges based on its neighbors' current distance estimates, without a global synchronized pass order. As long as every edge is eventually relaxed sufficiently many times, the same convergence argument applies, though the analysis becomes more delicate under asynchronous message delays and requires care to avoid the "count-to-infinity" problem when distances need to increase (a known practical issue in distance-vector routing, addressed by techniques like split-horizon and route poisoning).
What happens to the predecessor pointers if a negative cycle is detected?
Once a negative cycle reachable from the source is confirmed, any predecessor chain leading into or through vertices affected by that cycle is not trustworthy as a "shortest path," because no shortest path exists for those vertices — their true distance is . A robust implementation should, after detecting a negative cycle, perform an additional traversal to mark every vertex reachable from any vertex on a negative cycle (reachable, in turn, from the source) as having undefined distance, rather than reporting the last computed finite value.
Is Bellman-Ford considered a dynamic programming algorithm?
Yes. The recurrence is a textbook dynamic-programming recurrence over the number of edges allowed in a path, directly reflecting optimal substructure. Bellman-Ford's array of relaxation passes is an efficient way to compute this recurrence without explicitly storing a table indexed by both vertex and edge-count, collapsing the two-dimensional DP into a single evolving array — the same collapsing technique used in many space-optimized dynamic programs.