Sub topic 15
Modelling pitfalls and how to avoid them
This chapter assumes you have read the earlier chapters. You should know the neighbors function, breadth-first search (BFS) with a parent dictionary, and Dijkstra's algorithm. Most bugs in graph search come from the model, not the algorithm. The search runs correctly on a wrong graph and returns a wrong answer.
Pitfall 1: the state is missing a variable
A state must contain everything that changes what moves are legal or what the goal means. Suppose a grid has keys (a, b) and doors (A, B). A state of (row, col) is not enough. Standing on the same cell with a key and without it are different situations.
Fix this by adding the missing variable to the state. A bitmask of collected keys is hashable and compact.
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 key_moves(grid, state):
r, c, keys = state
for nr, nc in neighbors(grid, r, c):
ch = grid[nr][nc]
if ch.isupper() and not keys & (1 << (ord(ch) - ord('A'))):
continue # locked door
new_keys = keys
if ch.islower():
new_keys |= 1 << (ord(ch) - ord('a'))
yield nr, nc, new_keys
grid = ["S.aA.G"]
print(sorted(key_moves(grid, (0, 4, 0))))
print(sorted(key_moves(grid, (0, 2, 1))))The first call is at column 4 with no keys. It yields only (0, 5, 0), because the door at column 3 is locked. The second call is at column 2 holding key a. It yields (0, 1, 1) and (0, 3, 1), because the door is now open.
Pitfall 2: unhashable or shared state
Lists cannot go into a set or serve as dictionary keys. Convert them to tuples, frozensets, or strings. Never mutate a state in place when generating a successor. Build a new value instead, or every stored state changes with it.
Pitfall 3: bounds and indexing
- Python accepts
grid[-1], so a missing lower-bound check silently wraps to the opposite edge. - Check
nr < len(grid)for rows andnc < len(grid[0])for columns. Mixing them up fails only on non-square grids. - Keep one order,
(row, col), everywhere.
Pitfall 4: diagonal moves
BFS counts moves, so a diagonal step and a straight step both cost 1. If distance matters, a diagonal step costs about 1.414, and you need Dijkstra. Also decide whether a path may cut a corner between two walls, and enforce that rule in the neighbour function.
Pitfall 5: the wrong algorithm for the costs
| Situation | Use |
|---|---|
| All moves cost the same | BFS |
| Costs differ, none negative | Dijkstra |
| Costs differ and a good estimate of the remaining cost exists | A* |
| Only reachability or region counting | Flood fill |
Running BFS on weighted edges returns the fewest steps, not the lowest cost. Dijkstra gives wrong answers if any edge cost is negative.
Pitfall 6: marking visited too late
In BFS, mark a state as seen when you enqueue it, as parent does in shortest_path. If you mark it only when you dequeue it, the same state enters the queue many times and the search slows down.
Checklist
- List every quantity that can change, and confirm each one is in the state.
- Confirm that the state is immutable and hashable.
- Test the neighbour function on corners and edges.
- Match the algorithm to the edge costs.
Exercise
A maze has one-way teleporters that work only once. A solver uses states of (row, col) and BFS. Why can it return a wrong answer, and what change fixes it?
Show answer
Whether a teleporter is still usable depends on history, but the state does not record it. The same cell can be reached with a teleporter used or unused, and these are different situations. Add the set of used teleporters to the state, for example as a frozenset or a bitmask, so the state becomes (row, col, used).