Sub topic 5
Tracing Dijkstra's Algorithm Step by Step
This chapter runs the algorithm by hand on one small graph and records every decision in a table. You will see tentative distances drop, vertices get finalized, and predecessors change as better routes appear. If you can produce this table yourself, the heap-based code later in the tutorial will be easy to follow, and you will be able to debug it.
This chapter assumes you already know:
- how edge relaxation works, from the chapter "Edge Relaxation: Improving Distance Estimates"
- the greedy rule of always expanding the closest unvisited vertex, from "The Greedy Rule: Always Expand the Closest Vertex"
- adjacency lists, basic Python, and breadth-first search
The Example Graph
The graph is directed and has six vertices. The source is S. All weights are non-negative, which the algorithm requires. The weights were chosen so that almost every step improves an estimate made earlier. That gives you practice with the part of tracing that people most often get wrong.
The same graph as an adjacency list:
| Vertex | Outgoing edges (neighbor, weight) |
|---|---|
| S | (A, 4), (B, 1) |
| A | (C, 1), (D, 6) |
| B | (A, 2), (C, 5) |
| C | (D, 2), (E, 7) |
| D | (E, 1), (A, 1) |
| E | none |
The Bookkeeping You Track
A hand trace keeps three pieces of state for every vertex:
dist[v]is the tentative distance: the cost of the best path tovfound so far. It starts at 0 for the source and infinity (∞) for every other vertex.prev[v]is the predecessor: the vertex just beforevon that best path. It starts empty.- The finalized set holds the vertices whose distance can no longer change. It starts empty.
Each round does the same thing:
- Among the vertices that are not finalized and have a finite distance, pick the one with the smallest
dist. - Finalize it.
- Relax each of its outgoing edges
(u, v, w). Ifdist[u] + w < dist[v], setdist[v] = dist[u] + wandprev[v] = u.
The algorithm stops when no unfinalized vertex has a finite distance.
The Trace, Round by Round
Round 1: finalize S at 0
S is the only vertex with a finite distance, so it is chosen and finalized.
S→A: 0 + 4 = 4 < ∞. Setdist[A] = 4,prev[A] = S.S→B: 0 + 1 = 1 < ∞. Setdist[B] = 1,prev[B] = S.
Round 2: finalize B at 1
The candidates are A (4) and B (1). B is smaller.
B→A: 1 + 2 = 3 < 4. Setdist[A] = 3,prev[A] = B. The direct edge from S no longer gives the best route to A.B→C: 1 + 5 = 6 < ∞. Setdist[C] = 6,prev[C] = B.
Round 3: finalize A at 3
The candidates are A (3) and C (6).
A→C: 3 + 1 = 4 < 6. Setdist[C] = 4,prev[C] = A.A→D: 3 + 6 = 9 < ∞. Setdist[D] = 9,prev[D] = A.
Round 4: finalize C at 4
The candidates are C (4) and D (9).
C→D: 4 + 2 = 6 < 9. Setdist[D] = 6,prev[D] = C.C→E: 4 + 7 = 11 < ∞. Setdist[E] = 11,prev[E] = C.
Round 5: finalize D at 6
The candidates are D (6) and E (11).
D→E: 6 + 1 = 7 < 11. Setdist[E] = 7,prev[E] = D.D→A: 6 + 1 = 7, which is not less than 3. Nothing changes. A was finalized in round 3, and with non-negative weights a path through a later vertex can never beat a finalized distance.
Round 6: finalize E at 7
E has no outgoing edges. Every vertex is now finalized, so the algorithm stops.
The Full Trace Table
Each row shows the state after that round's relaxations. Bold marks a finalized distance. An arrow shows a value that changed in that round.
| Round | Finalized | S | A | B | C | D | E |
|---|---|---|---|---|---|---|---|
| 0 (init) | none | 0 | ∞ | ∞ | ∞ | ∞ | ∞ |
| 1 | S | **0** | →4 (S) | →1 (S) | ∞ | ∞ | ∞ |
| 2 | B | **0** | →3 (B) | **1** | →6 (B) | ∞ | ∞ |
| 3 | A | **0** | **3** | **1** | →4 (A) | →9 (A) | ∞ |
| 4 | C | **0** | **3** | **1** | **4** | →6 (C) | →11 (C) |
| 5 | D | **0** | **3** | **1** | **4** | **6** | →7 (D) |
| 6 | E | **0** | **3** | **1** | **4** | **6** | **7** |
Two patterns are worth noticing:
- The finalized distances come out in non-decreasing order: 0, 1, 3, 4, 6, 7. This always happens with non-negative weights. If your hand trace finalizes a smaller value after a larger one, you made a mistake.
- A tentative value can drop several times before it is finalized. E went from ∞ to 11 to 7. A finalized value never changes.
The Resulting Shortest-Path Tree
The final prev entries form a tree rooted at the source. Following prev back from any vertex gives its shortest path in reverse. A later chapter turns this into code.
The shortest path to E is S → B → A → C → D → E, with cost 1 + 2 + 1 + 2 + 1 = 7. It has five edges. A breadth-first search, which minimizes the number of edges, would choose S → A → D → E or S → B → C → E. Both of those cost 11.
Checking Your Trace with Code
The script below runs the same procedure with a plain linear scan instead of a heap and prints every decision. It is meant for checking hand traces, not for speed. The heap version comes in "Implementing Dijkstra's Algorithm with heapq".
INF = float("inf")
graph = {
"S": [("A", 4), ("B", 1)],
"A": [("C", 1), ("D", 6)],
"B": [("A", 2), ("C", 5)],
"C": [("D", 2), ("E", 7)],
"D": [("E", 1), ("A", 1)],
"E": [],
}
def trace(graph, source):
dist = {v: INF for v in graph}
prev = {v: None for v in graph}
dist[source] = 0
done = set()
step = 0
while True:
candidates = [v for v in graph if v not in done and dist[v] < INF]
if not candidates:
break
# Smallest distance first; ties broken alphabetically for a repeatable trace.
u = min(candidates, key=lambda v: (dist[v], v))
done.add(u)
step += 1
print(f"Round {step}: finalize {u} at {dist[u]}")
for v, w in graph[u]:
nd = dist[u] + w
if nd < dist[v]:
print(f" {u}->{v}: {dist[u]}+{w}={nd} < {dist[v]}, update")
dist[v] = nd
prev[v] = u
else:
print(f" {u}->{v}: {dist[u]}+{w}={nd} >= {dist[v]}, no change")
return dist, prev
dist, prev = trace(graph, "S")
for v in graph:
print(v, dist[v], prev[v])Running it prints:
Round 1: finalize S at 0
S->A: 0+4=4 < inf, update
S->B: 0+1=1 < inf, update
Round 2: finalize B at 1
B->A: 1+2=3 < 4, update
B->C: 1+5=6 < inf, update
Round 3: finalize A at 3
A->C: 3+1=4 < 6, update
A->D: 3+6=9 < inf, update
Round 4: finalize C at 4
C->D: 4+2=6 < 9, update
C->E: 4+7=11 < inf, update
Round 5: finalize D at 6
D->E: 6+1=7 < 11, update
D->A: 6+1=7 >= 3, no change
Round 6: finalize E at 7
S 0 None
A 3 B
B 1 S
C 4 A
D 6 C
E 7 DCommon Tracing Errors
| Error | What it looks like | Fix |
|---|---|---|
| Finalizing on discovery | Treating A as done at 4 as soon as S reaches it, like visiting a node in BFS | A vertex is final only when it is selected as the minimum |
| Overwriting without comparing | Setting `dist[C] = 6` in round 2 even though a smaller value was already there | Update only when the new total is strictly smaller |
| Forgetting `prev` | Distances are right but the path cannot be recovered | Change `prev[v]` every time `dist[v]` changes, and only then |
| Changing a finalized vertex | Lowering A after round 3 | With non-negative weights this never happens. If it seems to, recheck your arithmetic |
| Choosing by edge weight | Picking the cheapest edge out of the current vertex instead of the smallest `dist` overall | Compare tentative distances across all unfinalized vertices |
| Undirected edge used one way only | Missing a shorter route that goes "backwards" along an edge | In an undirected graph, list every edge in both directions |
Exercises
Exercise
Change the weight of edge B→A from 2 to 4 and trace again from S. What are the final distances and the shortest path to E?
Show answer
Round 1 finalizes S (A=4, B=1). Round 2 finalizes B: B→A gives 5, which is not less than 4, so A stays 4 with prev S; C=6. Round 3 finalizes A at 4: C drops to 5 (prev A), D=10. Round 4 finalizes C at 5: D drops to 7, E=12. Round 5 finalizes D at 7: E drops to 8; D→A gives 8 ≥ 4, no change. Round 6 finalizes E at 8. Final: S 0, A 4, B 1, C 5, D 7, E 8. The path to E is S → A → C → D → E.
Exercise
In the original trace, how many times was a tentative distance assigned to E, and in which rounds? Why does that matter for a heap-based implementation?
Show answer
E was assigned twice: 11 in round 4 and 7 in round 5. A heap-based version with lazy deletion pushes one entry per assignment, so the heap holds a stale (11, E) entry that must be skipped when it is popped.
Exercise
Add a vertex G with a single edge G→S of weight 1, and run the original trace from S. What happens to G?
Show answer
No edge leads into G, so it is unreachable from S. Its distance stays ∞, its predecessor stays None, and it is never finalized. The checker script stops once no unfinalized vertex has a finite distance and reports G as inf.