Sub topic 9
Why Negative Weights Break Dijkstra and What to Use Instead
This chapter assumes you already know the heap-based dijkstra function from earlier chapters and the greedy invariant: once a vertex is popped from the heap, its distance is final. That invariant depends on one condition, which is that every edge weight is non-negative. When an edge weight is negative, the invariant fails and Dijkstra can return wrong distances without raising any error.
The Failure Mode
Dijkstra finalizes a vertex because it assumes no path discovered later can be cheaper. Any later path leaves the frontier at a distance at least as large as the current one. With non-negative edges, the cost can only grow from there. A negative edge breaks that reasoning, because a path that looked more expensive at the frontier can become cheaper after it crosses the negative edge.
A Concrete Counterexample
import heapq
def dijkstra(graph, source):
dist = {source: 0}
prev = {}
heap = [(0, source)]
visited = set()
while heap:
d, u = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
for v, w in graph.get(u, []):
nd = d + w
if v not in dist or nd < dist[v]:
dist[v] = nd
prev[v] = u
heapq.heappush(heap, (nd, v))
return dist, prev
graph = {
"A": [("B", 2), ("C", 3)],
"B": [("D", 1)],
"C": [("B", -2)],
"D": [],
}
dist, _ = dijkstra(graph, "A")
print(dist["D"]) # prints 3, but the true shortest path A-C-B-D costs 2Here is the trace:
- Pop A (0). Set B = 2 and C = 3.
- Pop B (2) and mark it visited. Set D = 3.
- Pop C (3). Relaxing C→B gives 1, so
dist["B"]becomes 1 and the entry (1, B) is pushed. - Pop (1, B). B is already visited, so the entry is skipped as stale. The improvement never reaches D.
- Pop D (3). The final result is D = 3, which is wrong.
A Tempting Fix That Does Not Work
A common idea is to add a constant to every edge so that all weights become non-negative. That shifts each path's cost by the constant times its number of edges, so paths with more edges are penalized more. The ranking of paths can change, and the shortest path can change with it. The exercise below shows this happening.
Bellman-Ford
Bellman-Ford relaxes every edge in rounds. A shortest path with no repeated vertex has at most V − 1 edges, so V − 1 rounds of relaxing all edges are enough to reach every true distance. If one more round still improves some distance, the graph has a negative cycle reachable from the source, and shortest paths are undefined.
def bellman_ford(graph, source):
nodes = set(graph) | {v for u in graph for v, _ in graph[u]}
dist = {source: 0}
for _ in range(len(nodes) - 1):
changed = False
for u in graph:
if u not in dist:
continue
for v, w in graph[u]:
if v not in dist or dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
break
for u in graph:
if u in dist:
for v, w in graph[u]:
if v not in dist or dist[u] + w < dist[v]:
raise ValueError("negative cycle reachable from source")
return dist
graph = {
"A": [("B", 2), ("C", 3)],
"B": [("D", 1)],
"C": [("B", -2)],
"D": [],
}
print(bellman_ford(graph, "A")) # {'A': 0, 'B': 1, 'C': 3, 'D': 2}Bellman-Ford runs in O(VE) time, compared with O((V + E) log V) for heap-based Dijkstra. That extra cost is the price of handling negative weights.
Choosing an Algorithm
| Situation | Use | Time |
|---|---|---|
| All weights non-negative | Dijkstra (binary heap) | O((V + E) log V) |
| Negative weights, may contain cycles | Bellman-Ford | O(VE) |
| Negative weights, graph is a DAG | Relax edges in topological order | O(V + E) |
| All pairs, negative weights, no negative cycles | Johnson's algorithm: Bellman-Ford once to reweight, then Dijkstra from each vertex | O(VE log V) |
Johnson's algorithm is the correct form of the reweighting idea. It gives each vertex v a potential h(v) and replaces each edge weight w(u, v) with w(u, v) + h(u) − h(v). Along any path, the potentials of the interior vertices cancel out. Every path between the same two endpoints shifts by the same amount, so the ranking of paths is preserved.
Exercise
Add 2 to every edge in the counterexample graph so all weights are non-negative, then run Dijkstra. Which path to D does it report, and why is that the wrong answer for the original graph?
Show answer
The new weights are A→B 4, A→C 5, B→D 3, and C→B 0. The path A-B-D now costs 7 and A-C-B-D costs 8, so Dijkstra reports A-B-D. In the original graph, A-B-D costs 3 and A-C-B-D costs 2. The three-edge path was charged 6 extra and the two-edge path only 4, so adding the constant changed which path is shortest.
Exercise
Bellman-Ford finishes its V − 1 rounds, and an extra pass still lowers dist[x]. What does this tell you, and can Dijkstra give a meaningful answer for this graph?
Show answer
A negative cycle is reachable from the source, so distances to some vertices can be lowered forever and shortest paths are undefined. No algorithm can give finite shortest distances for the affected vertices. Dijkstra would silently return some numbers, but they would be meaningless.