Dijkstra returns the wrong distance with a negative edge. Fix it
Question
A billing router sends traffic across gateways A, B, C, and D. One link gives a rebate (-4), so edge weights can be negative.
| edge | weight |
|---|---|
B -> D | 1 |
C -> B | -4 |
A -> C | 6 |
A -> B | 4 |
The Dijkstra function below returns 5 for the shortest cost from A to D, even though A -> C -> B -> D costs 3. Explain why it fails, replace it with Bellman-Ford, and return None if a negative cycle is reachable from start.
import heapq def shortest_distances(nodes, edges, start): adj = {node: [] for node in nodes} for src, dst, weight in edges: adj[src].append((dst, weight)) dist = {node: float("inf") for node in nodes} dist[start], settled, heap = 0, set(), [(0, start)] while heap: cost, node = heapq.heappop(heap) if node in settled: continue settled.add(node) for dst, weight in adj[node]: if dst not in settled and cost + weight < dist[dst]: dist[dst] = cost + weight heapq.heappush(heap, (dist[dst], dst)) return dist nodes = ["A", "B", "C", "D"] edges = [("B", "D", 1), ("C", "B", -4), ("A", "C", 6), ("A", "B", 4)] print(shortest_distances(nodes, edges, "A")["D"]) # 5, should be 3
Show hints (3)
- "WHY DIJKSTRA FAILS"
Trace the pop order:
Aat 0,Bat 4,Dat 5, thenCat 6. WhenCpops, why can'tC -> B (-4)lowerB? - "RELAX ALL EDGES"
Any simple path across
Vnodes has at mostV - 1edges. Relax every edge(src, dst, weight)forV - 1full passes. - "DETECT NEGATIVE CYCLES"
Run one more pass (pass
V). If any reachable edge still lowersdist[dst], a negative cycle is reachable fromstart, so returnNone.
Show checked explanation
Dijkstra locks a node's distance the first time it leaves the heap. Here it settles B at 4 and D at 5 before popping C at 6, so it never uses C -> B (-4) to lower B to 2 and D to 3. Bellman-Ford relaxes every edge V - 1 times in O(V * E) time and checks pass V for a reachable negative cycle.
def shortest_distances(nodes, edges, start): dist = {node: float("inf") for node in nodes} dist[start] = 0 for step in range(len(nodes)): changed = False for src, dst, weight in edges: if dist[src] + weight < dist[dst]: if step == len(nodes) - 1: return None # reachable negative cycle dist[dst] = dist[src] + weight changed = True if not changed: break return dist nodes = ["A", "B", "C", "D"] edges = [("B", "D", 1), ("C", "B", -4), ("A", "C", 6), ("A", "B", 4)] print(shortest_distances(nodes, edges, "A")) print(shortest_distances(nodes, edges + [("D", "C", -1)], "A"))
{'A': 0, 'B': 2, 'C': 6, 'D': 3}
NoneCode and edge cases run on CPython 3.12.10; official documentation links checked. Checked by an editor other than the author.
Walkthrough
Dijkstra assumes that adding more edges can never shrink a path's cost. In our graph, that fails right away. After A pops at 0, the heap holds (4, "B") and (6, "C"). Next, B pops at 4, gets added to settled, and pushes (5, "D"). Then D pops at 5. When C finally pops at 6, C -> B (-4) offers cost 2 for B, but B is already settled and ignored.
Bellman-Ford makes no greedy lock-in. It sweeps all edges V - 1 times (3 passes for 4 nodes). Even with edges ordered opposite to A -> C -> B -> D, every pass extends shortest paths by at least one edge:
| pass | A | B | C | D | updates |
|---|---|---|---|---|---|
| start | 0 | inf | inf | inf | seed A = 0 |
| 1 | 0 | 4 | 6 | inf | A -> C, A -> B |
| 2 | 0 | 2 | 6 | 5 | B -> D (5), C -> B (2) |
| 3 | 0 | 2 | 6 | 3 | B -> D drops to 3 |
| 4 | 0 | 2 | 6 | 3 | no change; no negative cycle |
Why are V - 1 passes enough? Any simple path over V nodes uses at most V - 1 edges, and pass k finds every optimal path of up to k edges. Notice pass 3 was still needed to carry B = 2 forward to D = 3.
On the V-th pass (step == len(nodes) - 1), any further drop means a path of V edges beat every shorter path, so it repeated a node with a negative total loop. Adding ("D", "C", -1) forms C -> B -> D -> C with weight -4 + 1 - 1 = -4. Pass 4 still lowers D from 3 to 1 via B -> D, and the function returns None.
Time is O(V * E) and space is O(V). Breaking early when changed is false saves passes on graphs that settle quickly.
Common mistakes
- Dropping
settledfrom Dijkstra so popped nodes can re-enter the heap. That fixes this 4-node graph, but negative edges can trigger exponential re-queues and negative cycles loop forever. - Looping only
V - 2times. With edges listed in reverse order, pass 2 leavesDat 5 and misses the 3-edge pathA -> C -> B -> Dcosting 3. - Omitting the
V-th pass. Without that extra sweep, a reachable negative cycle silently returns bogus finite numbers instead ofNone. - Flagging an unreachable negative cycle as an error from
start. Becausefloat("inf") + weight < float("inf")is false for finite weights, unreachable cycles stay atinfand do not trigger a false alarm.
Follow-up questions
- "How do you mark only the nodes affected by a negative cycle instead of returning None?" After
V - 1passes, runVmore passes (one pass to catch each reachable negative cycle, plusV - 1to propagate-inf). Whenever an edge relaxes or starts at-inf, setdist[dst] = float("-inf"), or run BFS from every node relaxed on passV. On our cycle graph,B,C, andDbecome-infwhileAstays 0. - "What if the graph has negative edges but no cycles (a DAG)?" Topologically sort the nodes first, then relax outgoing edges in topological order. Each edge is relaxed once, cutting time from O(V * E) down to O(V + E).
- "Can you run Bellman-Ford on an undirected graph with a negative edge?" No. An undirected edge of weight
-2betweenXandYacts as two directed edgesX -> Y (-2)andY -> X (-2). As soon asXorYis reachable, walking back and forth forms a-4negative cycle.
What a strong answer covers
Pinpoints why Dijkstra settles B and D too early and why V - 1 edge passes cover every simple path. Uses pass V to detect reachable negative cycles, and contrasts O(V * E) with Dijkstra's O((V + E) log V).
Open in interactive practice deck →