Sub topic 6
Choosing a hashable state
This chapter assumes you know Python tuples, sets and dictionaries, and that you have seen a neighbour function and a breadth-first search (BFS) loop.
What a state must contain
A state is a value that stands for one vertex of the graph. Search code stores states in a seen set or as keys in a parent dictionary. Both need the state to be hashable, which means it has a hash value that never changes and it can be compared with ==.
A good state follows two rules:
- Complete: it holds everything that affects which moves are legal next, and what they lead to.
- Minimal: it holds nothing else. Two situations that behave the same should produce equal states.
In the jug puzzle, (a, b) is enough. The jug capacities never change, so they stay out of the state. The number of moves taken so far also stays out, because BFS tracks depth through the queue order.
Hashable and unhashable types
| Type | Hashable? | Use for state? |
|---|---|---|
| `int`, `str`, `bool` | Yes | Yes |
| `tuple` of hashable items | Yes | Best default |
| `frozenset` | Yes | For unordered collections |
| `list`, `set`, `dict` | No | Convert before storing |
Putting a list in a set fails right away:
seen = set()
seen.add(([0, 0], 3))This raises TypeError: unhashable type: 'list'. Use ((0, 0), 3) instead. For a board stored as a list of lists, convert it to a tuple of tuples when you generate the next state.
def freeze(board):
return tuple(tuple(row) for row in board)
def thaw(state):
return [list(row) for row in state]Use frozenset when order does not matter. For example, the set of collected keys frozenset({'a', 'b'}) equals frozenset({'b', 'a'}). A tuple ('a', 'b') does not equal ('b', 'a'), so it would give you two states for one situation.
Adding a missing variable
A grid cell is not always enough. Suppose a door D can be crossed only after you have picked up a key K. Standing on the same cell with and without the key are different situations, so the state is (row, col, has_key).
from collections import deque
def key_moves(grid, state):
r, c, has_key = state
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if not (0 <= nr < len(grid) and 0 <= nc < len(grid[0])):
continue
cell = grid[nr][nc]
if cell == '#' or (cell == 'D' and not has_key):
continue
yield (nr, nc, has_key or cell == 'K')
def fewest_moves(grid, start, goal):
first = (*start, False)
depth = {first: 0}
queue = deque([first])
while queue:
state = queue.popleft()
if state[:2] == goal:
return depth[state]
for nxt in key_moves(grid, state):
if nxt not in depth:
depth[nxt] = depth[state] + 1
queue.append(nxt)
return None
grid = ["S.K",
"##D",
"..G"]
print(fewest_moves(grid, (0, 0), (2, 2)))This prints 5. The path goes right twice to pick up the key, then down through the door twice. The goal test looks only at state[:2], so reaching G with or without the key counts.
If you left out has_key, the search would see (0, 1) twice and skip it the second time. It would miss the route back through the door.
Checking your state
- List every fact that changes during play, such as positions, items, and counters.
- Remove any fact that cannot change which moves are legal.
- Confirm that equal states always have the same set of next moves.
Exercise
A robot moves on a grid and must visit checkpoints A and B in any order before reaching the exit. Give a hashable state that is complete and minimal.
Show answer
Use (row, col, visited) where visited is a frozenset of the checkpoints reached so far, for example (2, 3, frozenset({'A'})). A tuple of two booleans (adone, bdone) also works. Do not include the path or the step count.