Sub topic 7
Reconstructing Paths with Parent Pointers
This chapter assumes you have read the earlier chapters on the BFS loop, on marking vertices visited when they are enqueued, and on BFS layers and shortest distances. You should already accept that BFS discovers every vertex at its shortest edge distance from the source. This chapter turns that distance into an actual route: the list of vertices you walk through to get from the start to the goal.
Why Distances Are Not Enough
A distance of 3 tells you the goal is three edges away. It does not tell you which three edges. Route planners, puzzle solvers, and network tools usually need the route itself. A navigation app has to say "turn left at B" as well as "4 minutes".
You could store a whole path for every vertex, but that costs a lot of memory. BFS already has all the information it needs at the moment it discovers each vertex: it knows which vertex it came from. Recording that one fact per vertex is enough to rebuild any shortest path later.
The Parent Map
A parent pointer is a record saying "vertex v was first discovered while BFS was expanding vertex u". We store these in a dictionary parent, where parent[v] = u. The start vertex has no parent, so it maps to a sentinel value such as None.
The dictionary does two jobs:
- Visited set. A vertex is in
parentexactly when it has been discovered. Checkingneighbor not in parentreplaces checkingneighbor not in visited. - BFS tree. Each entry is one edge of the BFS tree, stored from child to parent. Following the pointers from any discovered vertex leads back to the start.
Here is the standard version, which stops as soon as the goal is dequeued:
from collections import deque
def shortest_path(graph, start, goal):
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1]
for neighbor in graph[node]:
if neighbor not in parent:
parent[neighbor] = node
queue.append(neighbor)
return None
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(shortest_path(graph, 'A', 'F')) # ['A', 'B', 'D', 'F']The walk-back loop collects vertices from goal to start. That order is backwards, so the function reverses it with path[::-1] before returning.
Here is the BFS run on this graph. A discovers B and C. B discovers D. C sees that D is already in parent, so it skips D and discovers E. D discovers F. E sees F already discovered. When F is dequeued, the walk-back follows F → D → B → A.
Why the Walk-Back Gives a Shortest Path
There are two claims to check: the walk-back ends, and the path it produces is as short as possible.
It ends. Each vertex gets its parent once, at discovery, and is never reassigned. A parent was always discovered before its child. If you follow the pointers, discovery times strictly decrease, so you cannot loop. You must reach the only vertex with no parent, which is the start.
It is shortest. Say BFS discovers v while expanding u. From the layers chapter, u sits in some layer d and v lands in layer d + 1. So every parent pointer moves exactly one layer closer to the start. Walking back from a goal in layer k takes exactly k steps, and k is the shortest distance. The path has k edges, so no path is shorter.
It is a real path. Each pointer parent[v] = u came from scanning graph[u], so the edge u → v exists. In a directed graph the pointers run against the edge direction. That is why we reverse the collected list. You never need a reversed copy of the graph.
Building the Tree Once, Querying Many Goals
If you need routes to several destinations from one source, run BFS to completion once and keep the parent map. Each query is then a short walk.
from collections import deque
def bfs_tree(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
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': [],
'G': ['A'],
}
parent = bfs_tree(graph, 'A')
print(parent) # {'A': None, 'B': 'A', 'C': 'A', 'D': 'B', 'E': 'C', 'F': 'D'}
print(path_to(parent, 'E')) # ['A', 'C', 'E']
print(path_to(parent, 'F')) # ['A', 'B', 'D', 'F']
print(path_to(parent, 'G')) # NoneG has an edge into A, but no edge leads from A to G. BFS from A never discovers G, so G is missing from parent. The goal not in parent check returns None for unreachable vertices. Without that check, parent[node] would raise a KeyError.
You can also get the distance without storing it separately: it is len(path_to(parent, goal)) - 1.
Stopping at Discovery Instead of Dequeue
The first version checks for the goal when it is dequeued. You can check when it is discovered instead. The goal's parent is final at that moment, so the path is already known. Stopping early skips the rest of the goal's layer, and in wide graphs that layer can hold most of the vertices.
When you test at discovery, you have to handle start == goal separately, because the start is never "discovered" as a neighbor. This version also uses a private sentinel object instead of None, which makes it safe for graphs where None is a legitimate vertex label.
from collections import deque
_START = object()
def shortest_path_early(graph, start, goal):
if start == goal:
return [start]
parent = {start: _START}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in parent:
parent[neighbor] = node
if neighbor == goal:
path = [goal]
while parent[path[-1]] is not _START:
path.append(parent[path[-1]])
return path[::-1]
queue.append(neighbor)
return None
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(shortest_path_early(graph, 'A', 'F')) # ['A', 'B', 'D', 'F']
print(shortest_path_early(graph, 'A', 'A')) # ['A']
print(shortest_path_early(graph, 'F', 'A')) # NoneEdge Cases and Common Errors
| Situation | What goes wrong | Fix |
|---|---|---|
| Goal unreachable | `KeyError` during walk-back | Check `goal in parent` first, or return `None` when the queue empties |
| `start == goal` | Early-exit version never matches | Return `[start]` before the loop |
| Vertex labels include `None` | Walk-back stops at that vertex | Use a private sentinel object for the start |
| Forgot to reverse | Path runs goal to start | Reverse once at the end; avoid `insert(0, x)`, which is O(L) per call |
| Goal not a key in `graph` | `graph[node]` fails if it gets enqueued | Validate inputs or use `graph.get(node, [])` |
| Recursive walk-back | `RecursionError` on paths longer than about 1000 | Use a loop |
Which Shortest Path You Get
A graph often has several shortest paths. In the example, A → C → D → F has the same length as A → B → D → F. BFS returns whichever one the neighbor order favors: the first vertex to discover D becomes its parent. The result is deterministic for a fixed adjacency list. If you need a specific tie-break, such as the alphabetically smallest path, sort each neighbor list before running BFS. If you need every shortest path, store a list of parents for each vertex in the same layer. Then enumerate paths from those lists, keeping in mind that their number can grow exponentially.
Cost
Building the parent map is part of BFS, so it adds only O(1) work per discovered vertex. Total time stays O(V + E). The map holds one entry per discovered vertex, which is O(V) space. Reconstructing one path takes O(L) time, where L is its length, and L ≤ V − 1.
The common alternative is to push whole paths onto the queue, as in queue.append(path + [neighbor]). It is easy to write but copies a list on every discovery. That costs O(V · L) time and memory, which is O(V²) in the worst case, such as a long chain. Parent pointers avoid that cost entirely.
Exercise
In the example graph, change A's adjacency list to ['C', 'B'] and run shortest_path(graph, 'A', 'F'). What path is returned, and why does it differ from before?
Show answer
['A', 'C', 'D', 'F']. A now enqueues C before B, so C is expanded first and discovers D, making parent['D'] = 'C'. Both paths have three edges, and neighbor order decides which one gets recorded.
Exercise
A teammate's BFS sets parent[neighbor] = node for every neighbor and keeps a separate visited set that it checks only before enqueueing. On the undirected graph {1: [2], 2: [1, 3], 3: [2]} starting at 1, what can go wrong when reconstructing the path to 3?
Show answer
When 2 is expanded, it scans neighbor 1 and sets parent[1] = 2, overwriting the start's None. Walking back from 3 goes 3 → 2 → 1 → 2 → 1 ... forever. Parents must be assigned only when a vertex is first discovered.
Exercise
You need shortest routes from one depot to 10,000 delivery addresses in an unweighted road graph. Should you call shortest_path once per address, or something else? Give the time complexity of your approach.
Show answer
Run bfstree once from the depot, which takes O(V + E), then call pathto for each address in O(L) per query. Calling shortest_path 10,000 times would repeat BFS each time, up to O(10,000 · (V + E)).