Sub topic 7
Generating the graph on demand
This chapter assumes you can write a Python function with tuples, sets, and dictionaries. It also assumes you know what a queue is and what a vertex and an edge are. Earlier chapters showed how to write a grid neighbour function and how to encode a puzzle state as a hashable value. Here we put both to work.
Explicit and implicit graphs
An explicit graph is stored in memory as an adjacency list or matrix. An implicit graph is never stored. You hold only a start state and a function that returns the neighbours of any state. The graph exists as far as the search has asked about it.
This matters because most grids and puzzles are too large, or too awkward, to list in full. A 1000 by 1000 grid has a million cells. A puzzle can have far more states than that, and most are never reached. An implicit graph builds only the states the search visits.
Two functions, one shape
The grid neighbors function and the jug jug_moves function have the same job. Each takes a vertex and yields the vertices one edge away.
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, ncHere a vertex is a (row, column) pair. Bounds and walls decide which edges exist.
def jug_moves(state, caps=(3, 5)):
a, b = state
ca, cb = caps
yield (ca, b)
yield (a, cb)
yield (0, b)
yield (a, 0)
pour = min(a, cb - b)
yield (a - pour, b + pour)
pour = min(b, ca - a)
yield (a + pour, b - pour)Here a vertex is an (a, b) pair of water levels. The rules of the puzzle decide which edges exist. Both functions are generators, so they produce neighbours one at a time without building a list.
One generic search
Because the two functions share a shape, one search can serve both. The search below takes a start state, a goal test, and a move function. It does not know whether it is solving a maze or a puzzle.
from collections import deque
def solve(start, is_goal, moves):
parent = {start: None}
queue = deque([start])
while queue:
state = queue.popleft()
if is_goal(state):
path = []
while state is not None:
path.append(state)
state = parent[state]
return path[::-1]
for nxt in moves(state):
if nxt not in parent:
parent[nxt] = state
queue.append(nxt)
return None
def jug_moves(state, caps=(3, 5)):
a, b = state
ca, cb = caps
yield (ca, b)
yield (a, cb)
yield (0, b)
yield (a, 0)
pour = min(a, cb - b)
yield (a - pour, b + pour)
pour = min(b, ca - a)
yield (a + pour, b - pour)
print(solve((0, 0), lambda s: 4 in s, jug_moves))The goal is any state where one jug holds 4 units. The call passes jug_moves as the move function. To search a grid, you would wrap neighbors so it takes one cell argument: lambda cell: neighbors(grid, *cell).
The parent dictionary does two jobs. It records how each state was reached, and it marks which states are already discovered. The check nxt not in parent is what stops the search from looping forever when the graph has cycles.
Common errors
- Unhashable states. A list cannot be a dictionary key. Use tuples, or a
frozensetfor unordered parts. - Missing state variables. If two situations need different future moves but share one state value, the search merges them wrongly.
- Marking too late. Add a state to
parentwhen you enqueue it, not when you dequeue it. Otherwise the same state can enter the queue many times. - Mutating a state. A move function must build new states and leave the old one unchanged.
Exercise
A move function for a 3x3 sliding puzzle returns neighbours by editing the current state's list in place and yielding it. Why does the search give wrong answers, and what is the fix?
Show answer
The state is a list, so it is unhashable and cannot be stored in parent. Editing it in place also changes the state that is already stored and queued. The fix is to represent the state as a tuple and build a new tuple for each neighbour.