Zuerst das Quiz zu Kapitel 2Zuerst Kapitel 2 prüfen
Mach das Quiz zu Kapitel 2: 10 Fragen, bestanden mit 7 richtigen. Du kannst es beliebig oft wiederholen.
When Edges Go Negative
Kapitel 3, Lektion 2 von 4
Bellman-Ford: shortest paths that survive negative weights.
Auf Englisch gesprochen. Oben kannst du englische, arabische, deutsche, spanische oder französische Untertitel einschalten.
Schriftliche Lektion
8 Min. LesezeitAuf Englisch verfasst.
An electric car climbing a mountain pass burns energy. On the way down, its motor turns into a generator and charges the battery again. Measure every road by the energy it costs, and the downhill roads cost less than nothing: their weights are negative.
In the last lesson, one negative weight was enough to fool Dijkstra. Between 1955 and 1959 four researchers (Shimbel, Ford, Bellman and Moore) found the same cure independently, and today it carries two of their names: Bellman-Ford. This lesson covers how it works, why it needs exactly the passes it makes, how it catches a loop with no bottom, and where it runs today.
Trust nothing
Negative weights appear whenever a step can pay you back: a refund, a subsidy, energy won back downhill, or a trade that ends with more money than it started with.
In the car example, going round the lake costs 4 kWh. Going over the pass costs 5 kWh up and then −2 kWh down: 5 − 2 = 3. The cheapest route climbs.
Downhill roads cost less than nothing.
Remember last lesson's small graph (s → a 2, s → b 5, b → a −4, a → t 1). Dijkstra settled a at 2 and t at 3, and only later found the road from b with −4. The true distances were 1 and 2.
Relaxation was never the problem. Trust was. Dijkstra trusts a distance the moment it settles a vertex. Bellman-Ford trusts nothing until it has checked every edge enough times.
Pass after pass
- Start as before: 0 at the start, infinity everywhere else.
- Make a pass: go through the whole list of edges, in any fixed order, and relax every single one.
- Repeat, V − 1 times in all for a graph with V vertices.
- Make one extra pass to check the answer.
A pass can only lower a distance, never raise it, and every distance it holds is the cost of a real route that exists.
Behind it is Bellman's principle of optimality: the best way to reach a vertex is the best way to reach one of the vertices just before it, plus one last edge. Each pass pushes good distances one edge further.
Run it by hand
Our example has five vertices and seven directed edges, two of them negative. We scan the edges in this fixed order, starting from A:
| # | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| Edge | B → D | D → E | B → E | C → B | A → B | A → C | C → D |
| Weight | 3 | −2 | 5 | −3 | 2 | 4 | 6 |
Five vertices, seven directed edges, and the scan order.
- Pass 1. The first four edges leave vertices we cannot reach yet, so nothing happens. Then A gives B 2 and C 4, and C gives D 10.
- Pass 2. B lowers D to 2 + 3 = 5, and D lowers E to 5 − 2 = 3. Then C → B, with weight −3, brings B down to 4 − 3 = 1.
- Pass 3. With B at 1, D drops to 4, and E drops to 2.
- Pass 4. Nothing changes.
The distances are final: B 1, C 4, D 4 and E 2. Follow the parents back from E and the route is A, C, B, D, E, straight through the negative edge: 4 − 3 + 3 − 2 = 2.
The final distances. Pass 4 changes nothing.
The order of the list matters. Scan the edges in topological order (A → B, A → C, C → B, C → D, B → D, B → E, D → E) and one pass settles everything. Our order needed three passes that changed something; the worst order for this graph needs all four. Whenever a pass changes nothing, you can stop early: every distance is already final.
Why V − 1 passes
Take any vertex, and a cheapest route to it.
If there is no negative cycle, that route never needs to visit a vertex twice: cutting out a loop cannot make it more expensive. So it has at most V − 1 edges.
Proof by induction. Before pass k, the vertex just before the last edge of the route (a route of k − 1 edges) is already correct. During pass k, that last edge is relaxed, so the end of the route becomes correct too.
After each pass, the correct distances reach one edge further.
And no distance can ever drop below the truth, because every value is the cost of a real route. So after V − 1 passes, every distance is exactly right, whatever order the edges come in.
No bottom
What if a cycle has a negative total? Take the triangle from our guide: A → B 2, B → C −5, C → A 1. Every lap costs 2 − 5 + 1 = −2. Go round once: −2. Ten times: −20. There is no cheapest route at all, because one more lap is always cheaper.
This is what the extra pass is for. After V − 1 passes, every honest distance is already final. If any edge can still be relaxed, the only explanation is a negative cycle.
To find the cycle itself, start at a vertex that just improved and follow its parents back V times. You are now certainly inside the cycle, and walking on along the parents traces it out.
The extra pass detects the cycle, and the parents find it.
A negative cycle that the start cannot reach does no harm. Its vertices stay at infinity, and every other distance is still correct.
The cost
Each pass looks at every edge once, and there are V − 1 passes, so Bellman-Ford takes O(V · E) time: far slower than Dijkstra on a large graph. On our example that is 4 passes × 7 edges = 28 checks.
A popular speed-up (often called SPFA) keeps a queue of the vertices whose distance just changed, and only re-checks the edges leaving them. On many graphs it is much faster, but the worst case stays the same.
A trap from our guide. If you store infinity as the largest integer, then infinity plus a negative weight looks smaller than infinity, and the algorithm invents routes to vertices it cannot reach:
Infinity is not a number.
Always skip an edge whose start is still at infinity.
In the world
Routers. Early internet routers ran Bellman-Ford together. In the Routing Information Protocol (RIP), a router knows only its neighbours, and routers keep sharing their distance tables until everyone agrees. Its weak spot is bad news: when a link fails, two routers can keep quoting each other's old routes, raising them one step at a time. This is the count to infinity problem.
Currency markets. Exchange rates multiply along a chain of trades. Take minus the logarithm of every rate, and products turn into sums. A loop of trades that returns more money than it started with becomes a negative cycle. With made-up rates, a dollar changed into euros at 0.9, then pounds at 0.8, then back at 1.4 comes home as 0.9 × 0.8 × 1.4 = 1.008 dollars. The three log weights add up to about −0.008, and Bellman-Ford sees the loop at once.
An arbitrage loop is a negative cycle.
Johnson's algorithm. The trap from the last lesson, adding 4 to every weight, has a real fix. Give each vertex v its own adjustment h(v), computed by Bellman-Ford, and use the new weights w(u, v) + h(u) − h(v). Every route from s to t shifts by the same amount, h(s) − h(t), so the order of routes is kept, and no weight stays negative.
On last lesson's graph, h is 0 for s, −4 for a, 0 for b and −3 for t. The new weights are s → a 6, s → b 5, b → a 0 and a → t 0. Dijkstra now correctly finds s, b, a, t, costing 5, and subtracting the shift of 3 gives the true distance 2.
Johnson's reweighting: no negative weight, and the same best route.
In Python, the whole algorithm, extra pass included, is short:
def bellman_ford(vertices, edges, start):
dist = {v: float("inf") for v in vertices}
parent = {}
dist[start] = 0
for _ in range(len(vertices) - 1):
changed = False
for u, v, w in edges:
if dist[u] != float("inf") and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
parent[v] = u
changed = True
if not changed:
break # stop early
for u, v, w in edges: # the extra pass
if dist[u] != float("inf") and dist[u] + w < dist[v]:
raise ValueError("negative cycle")
return dist, parent
edges = [("B", "D", 3), ("D", "E", -2), ("B", "E", 5), ("C", "B", -3),
("A", "B", 2), ("A", "C", 4), ("C", "D", 6)]
bellman_ford("ABCDE", edges, "A")[0] # {'A': 0, 'B': 1, 'C': 4, 'D': 4, 'E': 2}
Key ideas
- Bellman-Ford relaxes every edge, pass after pass, and trusts no distance early.
- A cheapest route has at most V − 1 edges, so V − 1 passes are enough; after pass k, every route of at most k edges is correct.
- One extra pass that still improves something proves there is a negative cycle, and following parents back V times finds it.
- It runs in O(V · E) time: slower than Dijkstra, but it copes with negative weights.
Check yourself
1. A graph has 6 vertices and 10 edges. At most how many edge checks does Bellman-Ford make before the extra pass?
2. In the example, change C → B from −3 to −1. What are the distances now?
3. A cycle has weights 3, −4 and 2. Is it a negative cycle?
Practice on the platform
The Bellman-Ford guide explains every phase, with the pseudocode. In the Bellman-Ford visualizer, import the example as an edge list, in the same order, and run it from A: one, four, four and two, the same distances we found by hand.
Als Nächstes