Sub topic 22
Dijkstra's algorithm and why it fails with negative edges
Prerequisites
This chapter assumes you know binary heaps (insert and extract-min in O(log n)) and adjacency lists. It also assumes you know edge relaxation, covered in the previous chapter: if dist[u] + w < dist[v], set dist[v] = dist[u] + w.
The idea
Dijkstra's algorithm solves single-source shortest paths on a graph whose edge weights are all non-negative. It keeps a set of settled vertices whose distances are final. At each step it picks the unsettled vertex with the smallest tentative distance, settles it, and relaxes its outgoing edges.
This is a greedy algorithm. The greedy choice is "the closest unsettled vertex already has its true distance." The choice is safe only when no edge has a negative weight.
Implementation
The code below uses Python's heapq as a binary min-heap. Python has no decrease-key operation. Instead, the code pushes a new (distance, vertex) entry each time a distance improves. It then skips stale entries when they are popped.
import heapq
def dijkstra(graph, source):
dist = {u: float('inf') for u in graph}
dist[source] = 0
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue
for v, w in graph[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd
heapq.heappush(heap, (nd, v))
return dist
g = {'A': [('B', 1), ('C', 4)], 'B': [('C', 2), ('D', 6)], 'C': [('D', 3)], 'D': []}
print(dijkstra(g, 'A')) # {'A': 0, C': 3, 'D': 6}The line if d > dist[u]: continue discards st it the result stays correct, but the running time can grow.
Tracing by hand
GATE questions often ask for the order in which vertices are settled. Trace the graph above from A.
| Step | Settled vertex | dist A | dist B | dist C | dist D |
|---|---|---|---|---|---|
| Start | none | 0 | inf | inf | inf |
| 1 | A | 0 | 1 | 4 | inf |
| 2 | B | 0 | 1 | 3 | 7 |
| 3 | C | 0 | 1 | 3 | 6 |
| 4 | D | 0 | 1 | 3 | 6 |
At step 2, the edge B -> C gives 1 + 2 = 3, which beats 4. At step 3, the edge C -> D gives 3 + 3 = 6, which beats 7.
Why it is correct
Claim: when vertex u is extracted from the heap, dist[u] is the true shortest distance.
Suppose a shorter path to u existed. That path must leave the settled set at some edge (x, y). Here x is settled and y is not. By then dist[y] is at most dist[x] + w(x, y), because x was relaxed when it was settled. Since all weights are non-negative, the rest of the path from y to u adds at least 0. So dist[y] is at most the length of the shorter path, and that length is less than dist[u]. But the algorithm chose u because dist[u] was the minimum among unsettled vertices. That contradicts dist[y] < dist[u].
The step that uses non-negativity is "the rest of the path adds at least 0." It is also an exchange argument in disguise: any path to u can be replaced by the one through the settled set without getting longer.
Why negative edges break it
Consider this graph, with source S:
S -> Awith weight 2S -> Bwith weight 3B -> Awith weight -2
The true shortest distance to A is 3 + (-2) = 1, going through B.
Dijkstra settles A first with distance 2, since 2 is smaller than 3. It never revisits A, so it reports 2. The settled distance was not final, because a later vertex (B) offered a cheaper route through a negative edge.
import heapq
def dijkstra(graph, source):
dist = {u: float('inf') for u in graph}
dist[source] = 0
heap = [(0, source)]
settled = set()
while heap:
d, u = heapq.heappop(heap)
if u in settled:
continue
settled.add(u)
for v, w in graph[u]:
if v not in settled and d + w < dist[v]:
dist[v] = d + w
heapq.heappush(heap, (dist[v], v))
return dist
bad = {'S': [('A', 2), ('B', 3)], 'A': [], 'B': [('A', -2)]}
print(dijkstra(bad, 'S')) # {'S': 0, 'A': 2, 'B': 3} (true dist A is 1)This version tracks settled vertices explicitly, so a settled vertex is never updated. It prints 2 for A, which is wrong. The version in the implementation section would re-push A with distance 1. It would then give the right answer here, but its running time is no longer bounded by O((V + E) log V). With negative cycles reachable from the source, it can loop forever.
Complexity
The cost depends on the priority queue.
| Priority queue | Time |
|---|---|
| Binary heap with adjacency list | O((V + E) log V) |
| Fibonacci heap | O(E + V log V) |
| Unsorted array with adjacency matrix | O(V^2) |
With the lazy-deletion heap, at most E entries are pushed, so there are at most E pops at O(log E) each. Since E is at most V^2, log E is at most 2 log V, which is O(log V). The array version scans all V vertices to find the minimum, V times, which suits dense graphs where E is close to V^2.
Common errors
- Applying Dijkstra to a graph with any negative edge. Check the weights first.
- Confusing "settled order" with "discovery order." The settled order is by final distance.
- Forgetting that ties can be broken in any order, so a GATE question asking for "the" order usually has distinct distances.
- Assuming the shortest-path tree is unique. When two paths tie, more than one tree is valid.
- Treating undirected graphs with a negative edge as fine. An undirected negative edge is a negative cycle (go back and forth), so no shortest path exists.
Exercise
A graph has edges S->A (4), S->B (1), B->A (2), A->C (1), B->C (5). Run Dijkstra from S. List the vertices in the order they are settled, with their final distances.
Show answer
S (0), B (1), A (3), C (4). After S: A=4, B=1. B is settled next. Relaxing B gives A=3 and C=6. A is settled at 3, and relaxing A->C gives C=4, which beats 6. C is settled last at 4.
Exercise
Give a three-vertex graph with one negative edge where Dijkstra with a settled set returns a wrong distance, and state the correct distance.
Show answer
Take S->A (5), S->B (6), B->A (-3). Dijkstra settles A at 5 before B is processed, so it reports 5. The true distance to A is 6 + (-3) = 3.
Exercise
A graph has V = 1000 vertices and E = 400000 edges. Is the binary-heap version or the array version better, and why?
Show answer
The array version at O(V^2) = 10^6 operations is better. The heap version costs about (V + E) log V, which is roughly 400000 x 10 = 4 x 10^6 operations. The graph is dense, so the simple scan wins.