Sub topic 9
Why Negative Weights Break Dijkstra and What to Use Instead
This chapter assumes you have read the earlier chapters on edge relaxation, the greedy rule, and the heap-based dijkstra function with lazy deletion. You should also be comfortable reading Big-O bounds and Python dictionaries. The full correctness proof comes in a later chapter. Here we only need its central claim: once a vertex is popped from the heap, its distance is final.
That claim depends completely on one assumption, that edge weights are never negative. This chapter shows what goes wrong when the assumption fails, why some common quick fixes don't work, and which algorithm to use instead.
Where Negative Weights Come From
Negative weights are not just a textbook curiosity. They show up whenever an edge represents a gain instead of a cost:
- Currency arbitrage. If you set the weight to
-log(rate), the product of exchange rates along a path becomes a sum of weights. A negative cycle then means a profitable arbitrage loop. - Energy or fuel models. An electric vehicle going downhill recovers charge, so that segment has negative cost.
- Scheduling with constraints. Difference constraints such as
x_j - x_i <= cbecome edges with weightc, andccan be negative. - Rewards in games or planning. Moving through a tile might grant points that offset the cost of movement.
If your edge weights come from data you don't control, check their sign before you call Dijkstra.
The Greedy Invariant and Why It Needs Non-Negative Weights
Dijkstra pops the vertex u with the smallest tentative distance d. It treats d as final because any other route to u must leave the visited set through some unvisited vertex x. That vertex already has a tentative distance of at least d, since otherwise x would have been popped first. With non-negative weights, the rest of that route from x to u can only add to the cost, so the route costs at least d.
A negative edge breaks the last step. The route through x can start at a cost of d or more and then drop below d when it crosses a negative edge. The "final" distance of u was never final.
A Concrete Failure
Here is the smallest graph that shows the problem clearly. Vertex B is reachable directly from A at cost 2, or through C at cost 3 + (−2) = 1.
The code below includes the dijkstra function from the implementation chapter, so it runs on its own.
import heapq
def dijkstra(graph, source):
"""graph: dict mapping node -> list of (neighbor, weight), weights >= 0."""
dist = {source: 0}
prev = {}
heap = [(0, source)]
visited = set()
while heap:
d, u = heapq.heappop(heap)
if u in visited:
continue # stale entry left by lazy deletion
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["B"]) # prints 1 (correct)
print(dist["D"]) # prints 3, but the true shortest path A-C-B-D costs 2Tracing the Failure
| Step | Popped | Action | dist after step |
|---|---|---|---|
| 1 | A (0) | Relax A→B to 2, A→C to 3 | A=0, B=2, C=3 |
| 2 | B (2) | B marked visited; relax B→D to 3 | A=0, B=2, C=3, D=3 |
| 3 | C (3) | Relax C→B: 3 + (−2) = 1 < 2, so B becomes 1 and (1, B) is pushed | A=0, B=1, C=3, D=3 |
| 4 | B (1) | B already visited, skipped as stale | unchanged |
| 5 | D (3) | D marked visited | unchanged |
The output is internally inconsistent. dist["B"] is 1, and there is an edge B→D of weight 1, yet dist["D"] is 3. The improvement to B arrived after B had already been expanded, so it never reached D.
Fixes That Don't Work
Adding a Constant to Every Weight
A tempting idea is to find the most negative weight and add its absolute value to every edge, so that all weights become non-negative. This changes the problem. A path with k edges gets k times the constant added, so paths with more edges are penalized more.
Apply +2 to the graph above. The weights become A→B 4, A→C 5, C→B 0, B→D 3. Now A-B-D costs 7 and A-C-B-D costs 8, so the shifted graph prefers A-B-D. In the original graph, A-C-B-D (cost 2) beats A-B-D (cost 3). The shortest path changed.
Removing the Visited Check
If you delete the if u in visited: continue line, a vertex can be expanded again whenever a cheaper entry for it is popped. On graphs with negative edges but no negative cycles, this version does return correct distances. The cost is speed: on adversarial inputs, the number of re-expansions can grow exponentially in the number of vertices. On a graph with a negative cycle, the loop never terminates. You lose the main reason to use Dijkstra.
Bellman-Ford: The Standard Alternative
Bellman-Ford uses the same relaxation step as Dijkstra but drops the greedy rule. Instead of choosing a vertex carefully, it relaxes every edge, repeatedly.
The key fact is this: if there is no negative cycle, some shortest path to each vertex uses at most V - 1 edges. After round i of relaxing all edges, every vertex whose shortest path has at most i edges has its correct distance. So V - 1 rounds are enough. If one more round still improves some distance, a negative cycle is reachable from the source and no shortest path exists.
def bellman_ford(graph, source):
"""graph: dict node -> list of (neighbor, weight). Weights may be negative.
Returns (dist, prev). Raises ValueError on a reachable negative cycle."""
vertices = set(graph)
for edges in graph.values():
for v, _ in edges:
vertices.add(v)
dist = {v: float("inf") for v in vertices}
dist[source] = 0
prev = {}
for _ in range(len(vertices) - 1):
changed = False
for u, edges in graph.items():
if dist[u] == float("inf"):
continue
for v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
prev[v] = u
changed = True
if not changed:
break # distances are stable; stop early
for u, edges in graph.items():
if dist[u] == float("inf"):
continue
for v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError("negative cycle reachable from source")
return dist, prev
graph = {
"A": [("B", 2), ("C", 3)],
"B": [("D", 1)],
"C": [("B", -2)],
"D": [],
}
dist, prev = bellman_ford(graph, "A")
print(dist["D"]) # 2
print(prev["D"], prev["B"]) # B C -> path A-C-B-D
cyclic = {
"A": [("B", 1)],
"B": [("C", -3)],
"C": [("B", 1)],
}
try:
bellman_ford(cyclic, "A")
except ValueError as e:
print(e) # negative cycle reachable from sourceThe prev map has the same shape as the one Dijkstra produces, so the reconstruct_path function from the previous chapter works unchanged.
Edge Cases Worth Knowing
- Unreachable negative cycles are harmless. The check skips vertices at infinite distance, so a negative cycle the source can't reach does not raise an error. That is the right behavior for a single-source query.
- Undirected graphs with a negative edge always contain a negative cycle. An undirected edge of weight −1 is two directed edges, and going back and forth costs −2. Bellman-Ford will report a cycle. You need a different problem formulation.
- Vertices affected by a cycle. If you want to report "distance is −∞" for each affected vertex instead of raising an error, mark every vertex that still improves in round
Vand propagate that mark to everything reachable from those vertices.
Choosing an Algorithm
| Algorithm | Negative weights | Detects negative cycles | Time |
|---|---|---|---|
| Dijkstra (binary heap) | No | No | O((V + E) log V) |
| DAG shortest path (topological order) | Yes | Not needed, no cycles | O(V + E) |
| Bellman-Ford | Yes | Yes | O(V · E) |
| SPFA (queue-based Bellman-Ford) | Yes | Yes, with a counter | O(V · E) worst case, often faster in practice |
| Johnson (all pairs) | Yes | Yes | O(V · E + V (V + E) log V) |
For a graph with 10,000 vertices and 50,000 edges, Bellman-Ford's worst case is about 5 × 10⁸ relaxations, while Dijkstra needs about 60,000 × 14 ≈ 8 × 10⁵ heap operations. That gap is why it often pays to restructure the problem so all weights are non-negative, for example by using a DAG formulation or Johnson-style potentials, rather than falling back to Bellman-Ford everywhere.
Exercise
In the failing example, Dijkstra reports dist["B"] = 1 correctly but dist["D"] = 3 incorrectly. Explain precisely why B ends up correct while D does not.
Show answer
B's distance is updated when C is expanded and relaxes the edge C→B, since that relaxation happens whenever C is popped. But B was already in the visited set, so the new heap entry (1, B) is skipped as stale and B is never expanded again. D's distance depends on B being expanded with its improved value, and that never happens, so D keeps the value 3 from B's earlier expansion at distance 2.
Exercise
Graph: S→A weight 1, S→B weight 4, B→A weight -5, A→T weight 1. Shift every weight by +5 so all become non-negative. Which S-to-T path does the shifted graph choose, and is it the true shortest path?
Show answer
Shifted weights are S→A 6, S→B 9, B→A 0, A→T 6. S-A-T costs 12 and S-B-A-T costs 15, so the shifted graph picks S-A-T. In the original graph, S-A-T costs 2 and S-B-A-T costs 4 + (-5) + 1 = 0, so S-B-A-T is the true shortest path. The shift penalized the path with more edges.
Exercise
Why is V - 1 the right number of rounds in Bellman-Ford, and what does an improvement in round V tell you?
Show answer
Without negative cycles, a shortest path never needs to repeat a vertex, so it has at most V - 1 edges. Each round extends correctness by at least one edge along every shortest path, so V - 1 rounds are enough. If any distance still improves in round V, then some "shortest" walk would need V or more edges, which means it repeats a vertex around a cycle of negative total weight reachable from the source.