Bellman-Ford finds single-source shortest paths and, unlike Dijkstra, works when some edge weights are negative and can flag when no answer exists.
Core idea
- Single-source shortest paths: from one source vertex, find the cheapest total edge weight to every other vertex.
- Works with negative edge weights (a leg that earns money, releases energy, etc.).
dist[]holds the best distance known so far per vertex. Start: source= 0, all others= infinity.
Relaxation (the one operation)
- To relax edge
u -> vof weightw: ifdist[u] + w < dist[v], setdist[v] = dist[u] + w. - Never makes a distance worse; only ever lowers it.
if dist[u] != INF and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
The algorithm
- Relax every edge,
V - 1times. - Why
V - 1: a shortest path (no negative cycle) visits each vertex at most once, so it has at mostV - 1edges. Each full round pushes correct answers one edge farther from the source, regardless of edge order. - Keep the guard
dist[u] != INFso an unreached vertex offers nothing (matters if “infinity” is a large int rather thanfloat("inf")).
Negative cycles
- Negative cycle: a loop whose weights sum to a negative number. If reachable from the source, there is no answer (distances fall toward negative infinity).
- Detect: run one extra round after the
V - 1. If any edge still relaxes, a negative cycle exists. ReturnNone. - An undirected edge of weight
-2is two directed edges summing to-4, so any negative undirected edge is automatically a negative cycle.
Cost
- Time
O(V*E):V - 1rounds timesEedges each. The extra pass adds one moreE, negligible. - Space
O(V): just thedistlist; edges are given, not copied.
Bellman-Ford vs Dijkstra
| Bellman-Ford | Dijkstra | |
|---|---|---|
| Negative edges | yes | no |
| Detects negative cycles | yes | no |
| Time | O(V*E) | O((V + E) log V) |
| Use when | some weights negative, or need cycle check | all weights non-negative, want speed |
Gotchas
- Running only one pass: settles only vertices one edge out; you must repeat
V - 1times. - Forgetting the extra pass: silently returns nonsense on a graph with a negative cycle.
- Confusing
V - 1withE - 1: rounds scale with vertices, not edges. - A negative cycle the source cannot reach is not detected and does not affect these paths.