Bellman–Ford algorithm

Also known as: Bellman-Ford

On this page 7

The Bellman–Ford algorithm computes the shortest paths from one source vertex to every other vertex in a weighted directed graph, even when some edges have negative weights. It also detects negative-weight cycles reachable from the source, situations in which no finite shortest path exists.

Among graph algorithms, Bellman–Ford is the standard choice when Dijkstra’s algorithm cannot be used safely. Named after Richard Bellman and Lester Ford Jr., who published versions in the 1950s, it is a classic example of dynamic programming and runs in O(V·E) time, where V is the number of vertices and E the number of edges.

How the Bellman–Ford algorithm relaxes edges

Bellman–Ford works by repeated edge relaxation. Each vertex keeps a distance estimate, initially zero for the source and infinity for all others. Relaxing an edge from u to v with weight w means checking whether dist[u] + w < dist[v]; if so, the algorithm lowers dist[v] and records u as the predecessor of v.

  1. Set the source distance to 0 and every other distance to infinity.
  2. Repeat V − 1 times: relax every edge in the graph once.
  3. Run one more pass over all edges; if any distance still decreases, a negative cycle is reachable.
  4. Otherwise, follow predecessor links backward to reconstruct each shortest path.

The bound of V − 1 iterations follows from a simple fact: a shortest path without cycles contains at most V − 1 edges. After pass k, every vertex whose shortest path uses at most k edges already has its correct final distance, so V − 1 passes cover all simple paths.

Complexity and key properties

The cost of Bellman–Ford is dominated by V − 1 full passes over E edges. This makes it markedly slower than Dijkstra’s algorithm on large graphs, but its simple structure brings advantages in correctness and distribution.

PropertyValueRemark
Time complexityO(V·E)O(V³) on dense graphs
Space complexityO(V)Distance and predecessor arrays
Negative edge weightsSupportedMain advantage over Dijkstra
Negative cycle detectionYesExtra pass after V − 1 iterations
Best case with early exitO(E)When no distance changes in a pass
Graph typeDirected or undirectedUndirected negative edges form cycles
Main properties of the Bellman–Ford algorithm

A practical early termination check stops the loop when a full pass changes no distance, since further passes cannot change anything either. On many real graphs, this reduces running time considerably, although the worst case remains O(V·E).

Bellman–Ford compared with other shortest-path algorithms

Bellman–Ford is one member of a family of shortest-path methods, and the right choice depends on edge weights, graph density and the number of sources. The comparison below summarizes the trade-offs.

AlgorithmScopeNegative weightsTime complexity
Bellman–FordSingle sourceYes, detects cyclesO(V·E)
Dijkstra’s algorithmSingle sourceNoO((V + E) log V) with a binary heap
Breadth-first searchSingle sourceUnweighted onlyO(V + E)
DAG shortest pathSingle source, acyclic graphsYesO(V + E) after topological sorting
Floyd–WarshallAll pairsYes, detects cyclesO(V³)
Johnson’s algorithmAll pairs, sparse graphsYesO(V·E + V² log V)
Shortest-path algorithms side by side

Dijkstra’s greedy strategy assumes that a settled vertex never improves later, which negative edges can violate. Bellman–Ford makes no such assumption and therefore stays correct. Johnson’s algorithm combines both: it runs Bellman–Ford once to reweight edges to non-negative values, then runs Dijkstra from every vertex.

Detecting negative cycles

A negative cycle is a cycle whose edge weights sum to less than zero. Traversing it repeatedly lowers path cost without limit, so shortest paths to any vertex reachable through it are undefined, not merely very small.

Bellman–Ford detects such cycles with the extra V-th pass. If any edge can still be relaxed, some vertex lies on or behind a negative cycle. To extract the cycle itself, the implementation follows predecessor links from that vertex V times, which guarantees landing inside the cycle, and then walks the loop until it repeats.

ObservationInterpretationAction
No edge relaxesAll distances are finalReport shortest paths
An edge relaxesReachable negative cycle existsReport the cycle or mark affected vertices
Distance remains infinityVertex is unreachableReport no path
Outcomes of the final verification pass

Practical applications and implementation pitfalls

The best-known application is distance-vector routing. Protocols such as the Routing Information Protocol (RIP) use a distributed form of Bellman–Ford in which each router shares its distance table with neighbors, so no router needs a map of the whole network. Finance offers another use: currency arbitrage detection converts exchange rates to negative logarithms, so a profitable trading loop appears as a negative cycle.

Implementation errors tend to recur in a few places, and most of them produce silently wrong distances rather than crashes.

MistakeConsequenceFix
Adding to infinityInteger overflow, false relaxationsSkip edges whose source distance is infinite
Only V − 2 passesLong paths remain wrongRun exactly V − 1 relaxation passes
Missing verification passNegative cycles go unnoticedAlways run the extra pass
Bidirectional negative edgeSpurious negative cycleModel undirected negative edges with care
Common implementation mistakes

Distributed versions add their own failure mode, the count-to-infinity problem: after a link failure, routers may keep increasing distances slowly in a loop. Techniques such as split horizon and a maximum hop count of 15 in RIP limit the damage.

In plain words

The Bellman–Ford algorithm finds the cheapest route from one starting point to every other point in a network, even when some connections pay money back instead of costing it.

It works patiently. It checks every connection and updates its best known prices. Then it repeats this until the answers settle. If prices still fall after that, a loop exists that lets someone gain endlessly. In that case, it reports the problem instead of a wrong answer.

A real-world example

A treasury analyst at a mid-sized trading firm monitors exchange rates among twelve currencies, giving 132 directed conversion edges. Each rate r becomes an edge weight of −log(r), so a sequence of trades that multiplies money above 1.0 turns into a path with a negative total weight.

Every minute, a scheduled job runs Bellman–Ford from an arbitrary currency through 11 relaxation passes plus one verification pass. One afternoon, the final pass still relaxes an edge, and following predecessor links reveals a loop from euro to yen to Swiss franc and back. After fees, the loop yields about 0.04 percent per cycle, so the system flags it for review, and the desk confirms that the opportunity disappears within seconds.