Sub topic 7
Reconstructing Paths with Parent Pointers
This chapter assumes you already know the BFS loop from earlier chapters: a deque used as a FIFO queue, vertices marked as visited when they are enqueued, and the fact that BFS reaches each vertex first along a path with the fewest edges. Here you will turn that fact into an actual path you can return.
What a parent pointer records
When BFS discovers a vertex v while processing vertex u, the edge u → v is the last edge of a shortest path to v. If you store parent[v] = u at that moment, every discovered vertex points back one step toward the source. Together these pointers form the BFS tree. The source is the tree's root and has no parent.
To rebuild a path to goal, start at goal and follow parent pointers until you reach the root. That walk produces the path backwards, so you reverse it at the end.
Building the parent map once
When you need paths to many targets from the same source, run BFS once to build the full parent map, then reconstruct on demand. The parent dictionary also works as the visited set, so you don't need a separate set.
from collections import deque
def bfs_parents(graph, start):
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in parent:
parent[neighbor] = node
queue.append(neighbor)
return parent
def path_to(parent, goal):
if goal not in parent:
return None # goal was never reached
path = []
node = goal
while node is not None:
path.append(node)
node = parent[node]
path.reverse()
return path
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
parent = bfs_parents(graph, 'A')
print(path_to(parent, 'F')) # ['A', 'B', 'D', 'F']
print(path_to(parent, 'E')) # ['A', 'C', 'E']
print(path_to(parent, 'Z')) # NoneFor a single target, you can stop early. Check node == goal right after popleft() and reconstruct immediately, as the shortest_path function in the earlier chapter does. This saves work in large graphs when the goal is close to the source.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Setting `parent[v]` each time `v` is seen | A later, longer route overwrites the shortest one | Assign only if `v not in parent` |
| Recording the parent at dequeue time | Same vertex can be enqueued many times, and parents may change | Record when enqueuing |
| Forgetting to reverse | Path comes out goal-to-source | Reverse once at the end |
| Using `None` as the root marker when `None` is a vertex | Loop stops too early | Stop when `node == start` instead |
| Not handling unreachable goals | `KeyError` on `parent[goal]` | Check membership first |
Cost
Reconstruction takes O(L) time, where L is the number of edges in the path. That is at most O(V) and adds nothing to the O(V + E) cost of BFS. The parent map takes O(V) space, which replaces the visited set instead of adding to it.
Exercise
Using the same graph, suppose A's neighbor list is changed to ['C', 'B']. What path does pathto(bfsparents(graph, 'A'), 'F') return, and why?
Show answer
['A', 'C', 'D', 'F']. C is dequeued before B, so C discovers D first and parent['D'] = 'C'. When B is processed later, D is already in parent and is not reassigned. F still gets parent D.
Exercise
A student writes parent[neighbor] = node outside the "if neighbor not in parent" check but still enqueues only unseen vertices. On the original graph, what does path_to return for F?
Show answer
['A', 'C', 'E', 'F']. When C is processed it overwrites parent['D'] with 'C'. When E is processed it overwrites parent['F'] with 'E'. The result still has three edges, but only by luck. In other graphs, a vertex found later along a longer route overwrites its parent and the returned path is no longer shortest.