Sub topic 3
Why Negative Weights Break Dijkstra and What to Use Instead
This chapter assumes you have the heap-based dijkstra from the previous chapter and know Big-O notation.
Why Negative Weights Break Dijkstra
Dijkstra treats a vertex's distance as final once the vertex is popped from the heap. If an edge has a negative weight, a path found later can still be cheaper. By that point the vertex has been marked visited, so the cheaper distance never reaches its neighbors.
import heapq
def dijkstra_to_target(graph, source, target):
dist = {source: 0}
heap = [(0, source)]
visited = set()
while heap:
d, u = heapq.heappop(heap)
if u in visited:
continue
if u == target:
return d # final once popped, because weights are non-negative
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
heapq.heappush(heap, (nd, v))
return None
graph = {"A": [("B", 2), ("C", 3)], "B": [("D", 1)], "C": [("B", -2)], "D": []}
print(dijkstra_to_target(graph, "A", "D")) # prints 3; true cost A-C-B-D is 2If any weight is negative, use Bellman-Ford instead. It relaxes every edge V−1 times, runs in O(VE) time, and detects negative cycles.
Running Time and Memory Use
| Priority queue | Time |
|---|---|
| Unsorted array | O(V²) |
| Binary heap (lazy deletion) | O((V + E) log V) |
| Fibonacci heap | O(E + V log V) |
With lazy deletion the heap can hold up to E entries. Since log E ≤ 2 log V, the bound is still O(E log V). Memory use is O(V + E).
Why the Greedy Choice Is Correct
The invariant is that when u is popped, dist[u] is the true shortest distance. Any other path to u has to leave the visited set through some unvisited vertex y. That vertex satisfies dist[y] ≥ dist[u], because otherwise y would have been popped first. Non-negative edges after y cannot lower the total below dist[u]. A negative edge would break exactly that last step.
Stopping Early When You Only Need One Target
The invariant means you can return as soon as the target is popped, as dijkstra_to_target does. In the worst case this saves nothing. When the target is close to the source, it often saves a lot of work.
Decrease-Key, Lazy Deletion, and Fibonacci Heaps
Textbook Dijkstra lowers an existing heap entry with a decrease-key operation. Python's heapq has no decrease-key, so the code pushes a duplicate entry and skips stale ones when they are popped. This is called lazy deletion. Fibonacci heaps do decrease-key in O(1) amortized time, but their large constant factors mean binary heaps are usually faster in practice.
From Dijkstra to A* Search
A orders the heap by dist[v] + h(v), where h estimates the remaining distance to the target. If h never overestimates the true distance and is consistent, A returns correct answers and usually expands fewer vertices than Dijkstra. Dijkstra is the special case h = 0.
Exercise
A graph has 10,000 vertices, 50,000 edges, and one edge of weight −1. Which algorithm should you use, and roughly how much work does it do?
Show answer
Use Bellman-Ford, because Dijkstra can give wrong answers with any negative edge. Its cost is O(VE), which is about 10,000 × 50,000 = 5×10⁸ edge relaxations in the worst case.