Why negative edges break Dijkstra; Bellman-Ford in brief
🌍 In real life. A courier pays its riders: riding from C to B on a delivery earns 4 taka, so that leg "costs" −4. Now the cheapest way from A to B might be to go the long way round through C and collect the money. Weights can be negative whenever a step gives something back: a refund, a cashback, an energy gain.
The idea in one sentence: Dijkstra settles a place once and never looks again, which is only safe when no road can make a route cheaper later; Bellman-Ford instead relaxes every edge, V − 1 times over, which works with negative weights and also detects a negative cycle.
Its words:
- negative weight: an edge that lowers a path's cost
- negative cycle: a loop whose weights add up to less than 0; going round it again and again makes the cost fall forever, so there is no shortest distance
- round: one pass that relaxes every edge once
Step by step, Bellman-Ford:
dist = {start: 0}- repeat V − 1 times: for every arrow
a → bwith weightw, ifdist[a] + wbeatsdist[b], lowerdist[b] - do one more round: if anything still improves, a negative cycle is reachable
First, watch Dijkstra on arrows with a negative one. It settles B at 2 before it reaches C, so the arrow C → B worth −4 comes too late:
Why V − 1 rounds are enough. A shortest path never needs to repeat a place (without negative cycles, a loop never helps), so it uses at most V − 1 edges. After round 1, every shortest path of 1 edge is found; after round 2, every one of 2 edges, because its last edge was relaxed after the rest of it was already right; and so on. After V − 1 rounds, all of them are. If a further round still improves something, some route keeps getting cheaper: that can only be a negative cycle.
What it costs, by counting. V − 1 rounds of E relaxations: O(V · E). For 1,000 places and 5,000 arrows that is 999 × 5,000, about 5,000,000 relaxations, against roughly 6,000 × 10 = 60,000 heap steps for Dijkstra. So use Dijkstra when every weight is 0 or more, and Bellman-Ford only when some are negative, or when the number of edges in a route is limited (as in the task below).
def bellman_ford(vertices, edges, start):
dist = {start: 0}
for _ in range(len(vertices) - 1): # a shortest path uses at most V - 1 arrows
for a, b, w in edges:
if a in dist and (b not in dist or dist[a] + w < dist[b]):
dist[b] = dist[a] + w
for a, b, w in edges: # one more round: still improving?
if a in dist and (b not in dist or dist[a] + w < dist[b]):
return None # a negative cycle: no shortest distance
return dist
arrows = [("A", "B", 2), ("A", "C", 5), ("C", "B", -4), ("B", "D", 3)]
print(bellman_ford(["A", "B", "C", "D"], arrows, "A"))
loop = [("A", "B", 1), ("B", "C", -2), ("C", "B", 1)]
print(bellman_ford(["A", "B", "C"], loop, "A"))Mistakes and edge cases.
- trusting Dijkstra with a negative weight: it can return wrong distances without any error, as the animation showed
- stopping after one round: one round only finishes the paths whose edges happen to come in the right order; it takes up to V − 1
- a negative undirected road: going back and forth along it is already a negative cycle, so negative weights only make sense on arrows
- reading this round's new values in a limited-flights search: when a route may use at most k + 1 edges, each round must read only last round's prices (copy them first), or one round can chain several edges
- unreachable places: a place never reached stays out of
dist; don't treat it as distance 0
Quiz
Why can Dijkstra give a wrong answer with a negative arrow?
- It settles a place for good, but a negative arrow found later could still make that place cheaper
- heapq can't hold negative numbers
- It loops forever
What does this print?
def bellman_ford(vertices, edges, start): dist = {start: 0} for _ in range(len(vertices) - 1): # a shortest path uses at most V - 1 arrows for a, b, w in edges: if a in dist and (b not in dist or dist[a] + w < dist[b]): dist[b] = dist[a] + w for a, b, w in edges: # one more round: still improving? if a in dist and (b not in dist or dist[a] + w < dist[b]): return None # a negative cycle: no shortest distance return dist print(bellman_ford(["A", "B", "C"], [("A", "B", 4), ("B", "C", -1), ("A", "C", 5)], "A"))What does this print?
def bellman_ford(vertices, edges, start): dist = {start: 0} for _ in range(len(vertices) - 1): # a shortest path uses at most V - 1 arrows for a, b, w in edges: if a in dist and (b not in dist or dist[a] + w < dist[b]): dist[b] = dist[a] + w for a, b, w in edges: # one more round: still improving? if a in dist and (b not in dist or dist[a] + w < dist[b]): return None # a negative cycle: no shortest distance return dist print(bellman_ford(["A", "B"], [("A", "B", 1), ("B", "A", -3)], "A"))Bellman-Ford on 100 places and 400 arrows: about how many relaxations?
- About 40,000: 99 rounds of 400
- About 500
- About 10,000
With 4 places, this sometimes misses a cheaper route that uses 3 arrows. Which line is wrong?
def bellman_ford(vertices, edges, start): dist = {start: 0} for _ in range(1): for a, b, w in edges: if a in dist and (b not in dist or dist[a] + w < dist[b]): dist[b] = dist[a] + w return dist
Coding tasks
Write
bellman_ford(vertices, edges, start):edgesare arrows(a, b, w)andwmay be negative. Return a dict of the cheapest distance to every place reachable fromstart, orNoneif a negative cycle can be reached.Cheap flights with few stops. Write
cheapest_with_stops(flights, src, dst, k): each flight is(a, b, price), one way. Return the cheapest price fromsrctodstusing at mostkstops in between (so at most k + 1 flights), or-1if there is none.