Sub topic 9
Recovering the path itself
This chapter assumes you can write a breadth-first search (BFS) with a queue and a visited set, and that you know how Python dictionaries and tuples work. It builds on the neighbors function from the previous chapters.
Why distance is not enough
A plain BFS can tell you that the goal is 7 steps away. It cannot tell you which 7 steps. To get the route, the search must remember how it reached each vertex.
The standard way is a parent link. When BFS first discovers a vertex, it records the vertex it came from. Each vertex then points back toward the start, and following those links from the goal gives the path in reverse.
Parent links replace the visited set
The code below uses a dictionary parent for two jobs. A key in parent means "already discovered". The value is the cell we came from. The start has parent None, which marks the end of every chain.
from collections import deque
def neighbors(grid, r, c, diagonal=False):
steps = [(-1, 0), (1, 0), (0, -1), (0, 1)]
if diagonal:
steps += [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for dr, dc in steps:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != '#':
yield nr, nc
def shortest_path(grid, start, goal):
parent = {start: None}
queue = deque([start])
while queue:
cell = queue.popleft()
if cell == goal:
path = []
while cell is not None:
path.append(cell)
cell = parent[cell]
return path[::-1]
for nxt in neighbors(grid, *cell):
if nxt not in parent:
parent[nxt] = cell
queue.append(nxt)
return None
grid = [
"..#.",
"..#.",
"....",
]
print(shortest_path(grid, (0, 0), (0, 3)))This prints [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (1, 3), (0, 3)]. The wall in column 2 forces the route around the bottom row. Moving down first happens to come before moving right in the step order, so ties between equally short routes are broken by that order.
How the reconstruction works
Once the goal is popped, the loop walks backward:
- Start at the goal and append it to
path. - Replace the current cell with its parent.
- Repeat until the cell is
None, which only the start has. - Reverse the list so it runs from start to goal.
Because BFS discovers each vertex first through a shortest route, the chain of parents from any vertex is a fewest-steps path to it. This is why you must set the parent only when nxt not in parent. Overwriting it later would replace a shortest route with a longer one.
Counting steps and other results
The path length in moves is len(path) - 1, since the path lists vertices. The same parent dictionary also answers other questions. Every key is a reachable vertex, so len(parent) is the size of the reachable region.
Common errors
- Forgetting to reverse. The walk goes goal to start, so the raw list is backwards.
- Updating parents on every visit. Only write a parent when the vertex is new.
- Using a falsy start. Testing
while cell:fails if a cell is(0, 0)? It does not, since a non-empty tuple is truthy, but states like0or an empty string would stop early. Compare withis not None. - Marking visited at pop time. This lets the same vertex enter the queue many times and wastes memory. Record the parent when you push.
- Storing whole paths in the queue. It works, but each entry copies a list. Parent links use one entry per vertex.
Exercise
In shortest_path, what would the function return if you removed the if nxt not in parent check and always wrote parent[nxt] = cell? Name two problems this causes.
Show answer
The search would revisit vertices and could loop forever on any grid with open neighbours, because cells would be pushed again and again. Even if it finished, a later discovery would overwrite the parent of a cell that already had a shortest route, so the reconstructed path could be longer than the fewest-steps path or even form a cycle that never reaches None.