Sub topic 2
Tracing Dijkstra's Algorithm Step by Step
This chapter assumes you know what edge relaxation is, the greedy rule of always expanding the closest unvisited vertex, basic Python, and Big-O notation.
A Hand Trace
Here is the example graph, starting from source A:
Each row of the table shows one vertex being finalized and the edges relaxed from it.
| Step | Pop (dist, vertex) | Relaxations | Tentative distances |
|---|---|---|---|
| 1 | (0, A) | B=4, C=1 | A0 B4 C1 |
| 2 | (1, C) | B: 3 < 4, D=6 | A0 B3 C1 D6 |
| 3 | (3, B) | D: 4 < 6 | A0 B3 C1 D4 |
| 4 | (4, D) | none | final |
The direct edge A→B costs 4, but the route through C costs 3. Relaxation picks this up before B is finalized.
Priority Queues and Binary Heaps
A priority queue is a structure that always returns the item with the smallest key. A binary heap is a priority queue stored as an array. Both push and pop run in O(log n) time. Python's heapq module provides a min-heap on top of a plain list. Tuples compare by their first element, so (distance, vertex) entries come out in distance order.
heapq has no decrease-key operation. Instead, the algorithm pushes a new entry each time a distance improves. When it later pops an old entry for a vertex that is already visited, it skips it. This is called lazy deletion. In the trace, (4, B) and (6, D) are entries of this kind.
Implementation with Path Recovery
The prev map records which vertex gave each vertex its best distance. To recover a path, start at the target and follow prev back to the source, then reverse the list.
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 # stale entry from 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
def reconstruct_path(prev, source, target):
if target != source and target not in prev:
return None # unreachable
path = [target]
while path[-1] != source:
path.append(prev[path[-1]])
path.reverse()
return path
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [],
}
dist, prev = dijkstra(graph, "A")
print(dist) # {'A': 0, 'B': 3, 'C': 1, 'D': 4}
print(reconstruct_path(prev, "A", "D")) # ['A', 'C', 'B', 'D']Exercise
Change the weight of C→B from 2 to 4 and rerun. What is dist["D"], and what path does reconstruct_path return?
Show answer
dist["D"] is 5 and the path is ['A', 'B', 'D']. Going through C now gives B a distance of 5, which does not beat the direct edge's 4. So prev["B"] stays "A", and D is reached through B at 4 + 1 = 5, which beats 6 through C.