Bellman-Ford and negative edges
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Dijkstra's algorithm is fast, but it trusts a place as soon as it is the closest, so one negative road can make it wrong. Bellman-Ford trusts nothing: it relaxes every road, in a fixed order, V − 1 times. Watch four places and four roads, one with a cost of −4, settle round by round, see why V − 1 rounds are always enough, and use one extra pass to catch a loop that pays you back. The lesson "Dijkstra's algorithm" covers the greedy method this one replaces.
Roads with a refund
Four places joined by one-way roads. Each road has a cost; the road from b to a costs −4, a refund. We want the cheapest total cost from s to every place. A negative road is allowed; a loop that pays back is not.
a directed graph with edge weights (costs)
a -> c cost 1
b -> a cost -4
s -> a cost 2
s -> b cost 5
the same roads in Python, as a list of (u, v, w):
edges = [("a", "c", 1), ("b", "a", -4), ("s", "a", 2), ("s", "b", 5)]اقرأ الدرس خطوة بخطوة
Roads with a refund
Four places joined by one-way roads. Each road has a cost; the road from b to a costs −4, a refund. We want the cheapest total cost from s to every place. A negative road is allowed; a loop that pays back is not.
a directed graph with edge weights (costs) a -> c cost 1 b -> a cost -4 s -> a cost 2 s -> b cost 5 the same roads in Python, as a list of (u, v, w): edges = [("a", "c", 1), ("b", "a", -4), ("s", "a", 2), ("s", "b", 5)]Dijkstra trusts too early
Dijkstra's algorithm settles the closest place first and never revisits it. It settles a at 2, then c at 3. But s→b→a→c costs 5 − 4 + 1 = 2. The refund comes too late: a (really 1) and c (really 2) are both wrong.
Dijkstra settles in order: s, a, c, b its answers: s 0 · a 2 · b 5 · c 3 true cheapest: s 0 · a 1 · b 5 · c 2 s -> b -> a -> c = 5 + (-4) + 1 = 2 < 3 so a (2, really 1) and c (3, really 2) are both wrong its proof assumes no road has a negative costRelax: keep the cheaper total
Start with d[s] = 0 and every other place at ∞, meaning not reached yet. Relaxing a road u→v with cost w asks: is d[u] + w less than d[v]? If yes, v gets that cheaper total. That is the only move.
d = {v: float("inf") for v in nodes} d["s"] = 0 d: s 0 · a ∞ · b ∞ · c ∞ relax(u, v, w): if d[u] + w < d[v]: d[v] = d[u] + w float("inf") + w is still inf, so a road out of an unreached place never changes anythingRound 1: try every road
Bellman-Ford tries every road in one fixed list order: a→c, b→a, s→a, s→b. a and b are still at ∞, so their roads do nothing yet. s→a gives a = 2, and s→b gives b = 5.
round 1 a→c ( 1): d[a] + w = ∞ (skip) b→a (-4): d[b] + w = ∞ (skip) s→a ( 2): d[s] + w = 0 + 2 = 2 < ∞ → d[a] = 2 s→b ( 5): d[s] + w = 0 + 5 = 5 < ∞ → d[b] = 5 d: s 0 · a 2 · b 5 · c ∞Round 2: the refund lands
Same list again. a→c gives c = 2 + 1 = 3. b→a gives 5 − 4 = 1, cheaper than 2, so a drops to 1. Unlike in Dijkstra, a place can get cheaper again and again.
round 2 a→c ( 1): d[a] + w = 2 + 1 = 3 < ∞ → d[c] = 3 b→a (-4): d[b] + w = 5 + (-4) = 1 < 2 → d[a] = 1 s→a ( 2): d[s] + w = 0 + 2 = 2, not < 1 s→b ( 5): d[s] + w = 0 + 5 = 5, not < 5 d: s 0 · a 1 · b 5 · c 3Round 3: c catches up
a→c now gives 1 + 1 = 2, so c drops from 3 to 2. Nothing else changes. The best route s→b→a→c has 3 roads, and it took 3 rounds to carry the news along it.
round 3 a→c ( 1): d[a] + w = 1 + 1 = 2 < 3 → d[c] = 2 b→a (-4): d[b] + w = 5 + (-4) = 1, not < 1 s→a ( 2): d[s] + w = 0 + 2 = 2, not < 1 s→b ( 5): d[s] + w = 0 + 5 = 5, not < 5 d: s 0 · a 1 · b 5 · c 2Why V − 1 rounds
After round k, every place whose cheapest route uses at most k roads is right. A route with no loop has at most V − 1 roads (V = number of places). Each round tries all E roads, so the work is O(V·E).
after round k: d[v] <= the cheapest cost of any route from s to v that uses at most k roads V = number of places = 4, E = number of roads = 4 3 rounds x 4 roads = 12 tries time O(V·E), extra space O(V) for d route s -> b -> a -> c: 3 roads = V - 1One more pass checks
Try every road once more. Nothing gets cheaper, so the answers are final: s 0, a 1, b 5, c 2. If a whole round ever changes nothing, the loop can also stop early.
check pass (lines 5 to 7) a→c ( 1): d[a] + w = 1 + 1 = 2, not < 2 b→a (-4): d[b] + w = 5 + (-4) = 1, not < 1 s→a ( 2): d[s] + w = 0 + 2 = 2, not < 1 s→b ( 5): d[s] + w = 0 + 5 = 5, not < 5 no road relaxes: return d d: s 0 · a 1 · b 5 · c 2A loop that pays back
Add a road c→b costing 2. The loop b→a→c→b costs −4 + 1 + 2 = −1, so every lap is cheaper and no cheapest total exists. After 3 rounds, the extra pass still improves a: a negative cycle.
add c -> b (2): loop b -> a -> c -> b = -4 + 1 + 2 = -1 after 3 rounds: s 0 · a 1 · b 4 · c 2 check pass: a→c ( 1): d[a] + w = 1 + 1 = 2, not < 2 b→a (-4): d[b] + w = 4 + (-4) = 0 < 1 → d[a] = 0 a road still relaxes after V - 1 rounds: return None (a negative cycle is reachable from s)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01d[u] = 3, d[v] = 5, and the road u → v costs −1. What does relaxing it do?
d[u] + w = 3 + (−1) = 2, which is less than 5, so d[v] becomes 2. Negative costs are relaxed exactly like positive ones.
02A graph has V = 10 places and E = 30 roads, and no negative cycle. How many rounds does Bellman-Ford need at most?
A cheapest route with no loop visits each place at most once, so it has at most V − 1 = 9 roads. Round k fixes every place whose cheapest route has k roads or fewer, so 9 rounds are enough (9 × 30 = 270 tries).
03Why does Dijkstra's algorithm give c = 3 instead of 2 on the lesson's graph?
Dijkstra assumes no later road can make a settled place cheaper. With the −4 road from b, a really costs 1, but Dijkstra keeps a at 2 and computes c from that old value, so a and c are both wrong.
04After V − 1 rounds, one more pass still finds a road u → v with d[u] + w < d[v]. What does that tell you?
Without a negative cycle, every total is final after V − 1 rounds. If anything still improves, a loop with negative total cost is reachable: going round it again is always cheaper, so there is no cheapest route.
05What is the running time of Bellman-Ford with V places and E roads?
It tries all E roads in each of V − 1 rounds, plus one check pass: about V·E tries, each O(1). O(E log V) is Dijkstra with a binary heap, which needs costs of 0 or more.
المسرد
- Weighted graph
- A graph whose edges carry a number, here a cost. A directed graph's edges are one-way.
- Negative edge
- An edge with a cost below 0, like a refund. Allowed in Bellman-Ford, not in Dijkstra's algorithm.
- d[v]
- The cheapest total cost from the start s to v found so far. It starts at 0 for s and ∞ (not reached) for every other place.
- Relax
- Look at an edge u → v with cost w: if d[u] + w < d[v], set d[v] = d[u] + w.
- Round (pass)
- One try of every edge, in a fixed list order. Bellman-Ford runs V − 1 rounds.
- Simple path
- A route that never visits the same place twice. It has at most V − 1 edges.
- Negative cycle
- A loop whose costs add up to less than 0. Going round it again is always cheaper, so no cheapest route exists.
الملاحظات والمصادر
- The bound comes from MIT 6.006 and CLRS §22.1: with no negative cycle, a cheapest route never repeats a place, so it has at most V − 1 roads, and round k fixes every place whose cheapest route has k roads or fewer. The list order only changes how many rounds are really needed, never the answer.
- This example lists the roads in a bad order on purpose (a→c first), so the news needs all 3 rounds. In the order s→b, b→a, a→c, s→a, one round would already be enough.
- Stopping as soon as a round changes nothing keeps the answer right and often saves time, but the worst case is still O(V·E). Sedgewick and Wayne also give a queue-based version that only retries roads out of places that just changed.
- Dijkstra's algorithm takes time proportional to E log V with a binary heap (Sedgewick and Wayne), much faster, but it needs every cost to be 0 or more. Bellman-Ford is the slower, general tool for graphs with negative costs.
- The code is real Python 3: bellman_ford("sabc", edges, "s") returns {'s': 0, 'a': 1, 'b': 5, 'c': 2}. With the road ("c", "b", 2) added it returns None.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 12: Bellman-Ford
- Sedgewick and Wayne, Algorithms 4th ed., §4.4 Shortest Paths
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §22.1 The Bellman-Ford algorithm
- Bellman–Ford algorithm (history and variants)
- Python built-in functions: float() and infinity
اختبار يتاح بعد الخطوة الأخيرة.