Bellman-Ford: Shortest Paths with Negative Edge Weights
Dijkstra's algorithm is fast, but it is only correct when no edge weight is negative. Negative weights are not exotic: a graph of currency exchanges can be turned into one, as can a schedule where some steps earn time back, or a cost model with rebates. For those graphs the standard single-source algorithm is Bellman-Ford. It is slower, O(VE) instead of O((V + E) log V), but it gets negative edges right, and it does something Dijkstra's algorithm cannot: it detects a negative cycle, the situation in which shortest paths do not exist at all.
Examples use Python 3.10 or later and only the standard library.
Relaxation, repeated
Like Dijkstra's algorithm, Bellman-Ford keeps a tentative distance for every vertex (0 for the source, infinity elsewhere) and improves it by relaxing edges: for an edge u to v of weight w, if dist[u] + w is smaller than dist[v], set dist[v] to dist[u] + w.
The difference is in which edges get relaxed and when. Dijkstra's algorithm chooses vertices greedily and relaxes each edge once. Bellman-Ford makes no choices. It relaxes every edge, in any fixed order, and repeats that whole pass V - 1 times. Then it makes one extra pass as a check.
def bellman_ford(vertices, edges, source):
dist = {v: float("inf") for v in vertices}
dist[source] = 0
for round_no in range(1, len(vertices)): # V - 1 rounds
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
print(f"no change in round {round_no}, stopping early")
break
for u, v, w in edges: # one extra check
if dist[u] + w < dist[v]:
raise ValueError(f"negative cycle reachable from {source}")
return dist
vertices = ["A", "B", "C"]
edges = [("A", "B", 2), ("A", "C", 3), ("C", "B", -2)]
print(bellman_ford(vertices, edges, "A"))
vertices = ["S", "B", "C", "D"]
edges = [("S", "B", 4), ("B", "C", 2), ("C", "D", -4), ("D", "B", 1)]
try:
print(bellman_ford(vertices, edges, "S"))
except ValueError as err:
print(err)
no change in round 2, stopping early
{'A': 0, 'B': 1, 'C': 3}
negative cycle reachable from S
The first graph is the one that defeats Dijkstra's algorithm in the Dijkstra guide: A to B with weight 2, A to C with weight 3, and C to B with weight -2. In round 1 the edges are relaxed in the listed order, so B becomes 2, C becomes 3, and then C to B lowers B to 1. Round 2 changes nothing, so the loop stops early, and the result {'A': 0, 'B': 1, 'C': 3} is correct. Dijkstra's algorithm returned 2 for B.
The second graph contains the cycle B to C to D to B with total weight 2 + (-4) + 1 = -1. Every trip around it makes the distances smaller, so after V - 1 rounds an edge can still be relaxed, and the extra pass raises the error.
Why V - 1 rounds are enough
The key fact: after round k, every dist[v] is at most the length of the shortest path from the source to v that uses at most k edges. That holds for k = 0 (only the source has a finite distance), and if it holds after round k, then round k + 1 relaxes the last edge of every shortest path with k + 1 edges, so it holds after round k + 1 too.
If the graph has no negative cycle reachable from the source, some shortest path to each vertex is simple: it never repeats a vertex, because a repeated vertex means a cycle, and removing a cycle of non-negative weight never makes a path longer. A simple path visits at most V vertices, so it has at most V - 1 edges. After V - 1 rounds every shortest path has been covered, and all distances are final.
That gives the cycle test for free. If the distances are final, no edge can be relaxed any more. So if the extra pass still finds an edge that improves a distance, the assumption failed: there is a negative cycle reachable from the source. In that case "the shortest path" to any vertex reachable from the cycle is undefined, because you can always go around the cycle once more and get a smaller total. A negative cycle that the source cannot reach does not affect the answer and is not reported; its vertices simply stay at infinity.
Running time
Each round looks at all E edges, and there are V - 1 rounds plus one check, so Bellman-Ford takes O(VE) time and O(V) extra space for the distances. On a dense graph, where E is close to V^2, that is O(V^3).
The early exit is a cheap and useful improvement: if a full round changes nothing, no later round can either, so you can stop. In the run above the first graph finished after round 2 instead of running all its rounds. The worst case is still O(VE), since some graphs and edge orders need all V - 1 rounds, but on many inputs the loop stops much sooner. When you exit early, the extra check pass can be skipped too, since a round with no change already proves no edge can be relaxed.
Dynamic programming in disguise
The "at most k edges" fact is a dynamic programming recurrence. Let D(k, v) be the length of the shortest path from the source to v using at most k edges. Then D(0, v) is 0 at the source and infinity elsewhere, and
D(k, v) = min(D(k - 1, v), min over edges u to v of D(k - 1, u) + w(u, v)).
The states are (k, v) pairs, V of them per round, and filling one round costs O(E) in total, which gives the same O(VE). The program below follows the recurrence strictly by copying the previous round, so each line shows exactly the shortest distances using at most k edges:
def at_most_k_edges(vertices, edges, source):
inf = float("inf")
prev = {v: inf for v in vertices}
prev[source] = 0
print("k=0", prev)
for k in range(1, len(vertices)):
cur = dict(prev) # paths with at most k edges
for u, v, w in edges:
if prev[u] + w < cur[v]:
cur[v] = prev[u] + w
print(f"k={k}", cur)
prev = cur
return prev
vertices = ["A", "B", "C", "D"]
edges = [("C", "D", 1), ("B", "C", 1), ("A", "B", 1), ("A", "D", 5)]
at_most_k_edges(vertices, edges, "A")
k=0 {'A': 0, 'B': inf, 'C': inf, 'D': inf}
k=1 {'A': 0, 'B': 1, 'C': inf, 'D': 5}
k=2 {'A': 0, 'B': 1, 'C': 2, 'D': 5}
k=3 {'A': 0, 'B': 1, 'C': 2, 'D': 3}
The direct edge A to D costs 5, but the three-edge path A, B, C, D costs 3, and it appears only at k = 3. Because each round reads only the previous round's values, the edge order makes no difference to this version. The usual in-place version reuses values updated earlier in the same round, so it is at least as good after each round; with the edges listed as A to B, B to C, C to D it would settle the whole chain in a single round. Either way, V - 1 rounds are enough. If DP is new to you, dynamic programming explained covers states and recurrences from the start.
Choosing a shortest-path algorithm
| Graph | Algorithm | Time |
|---|---|---|
| Unweighted (or all weights equal) | BFS | O(V + E) |
| Non-negative weights | Dijkstra with a binary heap | O((V + E) log V) |
| Negative weights allowed, or a negative cycle must be detected | Bellman-Ford | O(VE) |
| Directed acyclic graph, any weights | Relax edges in topological order | O(V + E) |
| All pairs of vertices | Floyd-Warshall | O(V^3) |
Two rows need a sentence each. In a DAG, processing vertices in topological order and relaxing each vertex's outgoing edges once gives correct shortest paths even with negative weights, because when a vertex is processed every path into it has already been considered (there are no cycles to come back around). Floyd-Warshall computes the distance between every pair of vertices with a triple loop over a V by V table, in O(V^3) time and O(V^2) space, and also handles negative edges as long as there is no negative cycle.
Common mistakes
- Undirected graphs with a negative edge. An undirected edge with negative weight is a negative cycle by itself (go back and forth), so Bellman-Ford will report one. Shortest simple paths with negative undirected edges are a different, much harder problem.
- Stopping after V - 1 rounds without the check. You get numbers either way; only the extra pass tells you whether they mean anything.
- Overflow in fixed-width languages. Using a large integer for infinity and adding a negative weight to it can produce a wrong finite value. Skip edges whose source is still at infinity. Python's
float("inf")stays infinite when you add a number, so the code above is safe.
History
The algorithm is named after Richard Bellman, who published it in "On a routing problem" (Quarterly of Applied Mathematics, 1958), and Lester Ford Jr., who described the method in a 1956 RAND report on network flow theory.
Check yourself
- A graph has V = 5 and E = 8. How many edge relaxations does Bellman-Ford make in the worst case, counting the check pass? (5 passes of 8 edges: 40.)
- The extra pass improves a distance. Is the vertex whose distance changed necessarily on the negative cycle? (No. It is on the cycle or reachable from it.)
- Why can't Bellman-Ford stop after the round in which the target vertex first gets a finite distance? (A path with more edges and a smaller total can still appear in a later round, as A, B, C, D did at k = 3.)