Sub topic 16
Pattern Databases for Puzzle Search
This chapter assumes you have the astar function from the implementation chapter, and that you know what admissible and consistent heuristics are. It also builds on the relaxation idea from the chapter on designing heuristics. Here that idea turns into a concrete technique. You solve a simplified version of the puzzle exhaustively, ahead of time, and store the exact answers in a lookup table. A* then reads its heuristic from that table.
Why Manhattan Distance Runs Out of Steam
The sliding-tile puzzles are a 3×3 board with 8 tiles and a 4×4 board with 15 tiles. On these puzzles, Manhattan distance treats every tile as if the others did not exist. Real tiles get in each other's way. Two tiles in the right row but in swapped order need several extra moves, and Manhattan distance charges nothing for them. On the 15-puzzle, A* with Manhattan distance can expand hundreds of millions of nodes on hard instances.
A pattern database (PDB) is a precomputed table. For every possible placement of a chosen subset of tiles, it stores the exact number of moves needed to bring those tiles home. Because the table comes from solving the subproblem exactly, it captures the interactions between the tiles in the pattern.
The Abstraction
Choose a pattern, which is a subset of tiles such as {1, 2, 3, 4}. Then replace every other tile with an indistinguishable wildcard. Each concrete state maps to one abstract state, and every legal concrete move maps to a legal abstract move. As a result, the shortest abstract distance can never exceed the shortest concrete distance. This is the relaxation argument from the previous chapter: the abstract puzzle is easier, so its exact cost is a lower bound.
| Concrete state | Abstract state, pattern {1,2,3,4} |
|---|---|
| `8 6 7 / 2 5 4 / 3 _ 1` | `* * * / 2 * 4 / 3 _ 1` |
| `1 2 3 / 4 5 6 / 7 8 _` | `1 2 3 / 4 * * / * * _` |
The abstract space is small enough to enumerate completely. For the 8-puzzle with four pattern tiles plus the blank, there are 9 × 8 × 7 × 6 × 5 = 15,120 abstract states.
Building a PDB for the 8-Puzzle
Moves in sliding-tile puzzles are reversible. That means a breadth-first search outward from the abstract goal gives the distance to the goal from every abstract state.
from collections import deque
SIDE = 3
GOAL = (1, 2, 3, 4, 5, 6, 7, 8, 0) # 0 is the blank
def moves(state):
b = state.index(0)
r, c = divmod(b, SIDE)
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < SIDE and 0 <= nc < SIDE:
j = nr * SIDE + nc
s = list(state)
s[b], s[j] = s[j], s[b]
yield tuple(s)
def abstract(state, pattern):
return tuple(t if t in pattern or t == 0 else -1 for t in state)
def build_pdb(pattern):
start = abstract(GOAL, pattern)
dist = {start: 0}
queue = deque([start])
while queue:
s = queue.popleft()
for nxt in moves(s):
if nxt not in dist:
dist[nxt] = dist[s] + 1
queue.append(nxt)
return dist
PATTERN = frozenset({1, 2, 3, 4})
PDB = build_pdb(PATTERN)
def pdb_h(state):
return PDB[abstract(state, PATTERN)]
def manhattan_h(state):
total = 0
for i, t in enumerate(state):
if t:
g = t - 1
total += abs(i // SIDE - g // SIDE) + abs(i % SIDE - g % SIDE)
return total
hard = (8, 6, 7, 2, 5, 4, 3, 0, 1) # needs 31 moves
print(len(PDB), pdb_h(hard), manhattan_h(hard))The moves function works on abstract states unchanged, because wildcards (-1) slide into the blank like any other tile. This PDB counts every move, including wildcard moves. It is therefore the exact cost of the abstract problem, and it is consistent: one concrete move changes the abstract state by at most one abstract move, so h changes by at most 1.
Combining Heuristics with max
A single PDB covers only some tiles. It may score lower than Manhattan distance on states where the non-pattern tiles are far from home. The maximum of two admissible heuristics is admissible, and the maximum of two consistent heuristics is consistent. So you can take both:
calls = 0
def counted_neighbors(state):
global calls
calls += 1 # runs once per expanded node
for nxt in moves(state):
yield nxt, 1
for name, h in [("manhattan", manhattan_h),
("max(pdb, manhattan)", lambda s: max(pdb_h(s), manhattan_h(s)))]:
calls = 0
path, cost = astar(hard, GOAL, counted_neighbors, h)
print(name, cost, calls)Both runs report cost 31. The second should expand fewer nodes, because the combined heuristic dominates Manhattan distance. You can also build a second PDB on {5, 6, 7, 8} and take the maximum of all three values.
Additive Pattern Databases
Taking the max wastes information, because only one table contributes at a time. You would rather add the values from disjoint patterns. Adding the PDB above would overestimate, since wildcard moves get counted in every table that sees them. The fix is to charge cost only for moves of the pattern's own tiles. Every concrete move moves exactly one tile, and that tile belongs to at most one pattern. So the sum over disjoint patterns never counts a move twice, and it stays admissible.
With 0-cost and 1-cost moves, plain BFS is no longer correct. A 0-1 BFS fixes this: it pushes 0-cost successors to the front of the deque and 1-cost successors to the back. After the search, the blank's position does not affect the cost of pattern-tile moves. Taking the minimum over blank positions shrinks the table to pattern-tile positions only.
def build_additive_pdb(pattern):
start = abstract(GOAL, pattern)
dist = {start: 0}
dq = deque([start])
while dq:
s = dq.popleft()
b = s.index(0)
for nxt in moves(s):
cost = 1 if nxt[b] in pattern else 0 # tile that slid into b
nd = dist[s] + cost
if nd < dist.get(nxt, float('inf')):
dist[nxt] = nd
if cost == 0:
dq.appendleft(nxt)
else:
dq.append(nxt)
order = sorted(pattern)
table = {}
for s, d in dist.items():
key = tuple(s.index(t) for t in order)
table[key] = min(d, table.get(key, float('inf')))
return order, table
PARTS = [build_additive_pdb({1, 2, 3, 4}), build_additive_pdb({5, 6, 7, 8})]
def additive_h(state):
return sum(table[tuple(state.index(t) for t in order)]
for order, table in PARTS)
print(additive_h(hard), manhattan_h(hard))The additive heuristic is always at least as large as Manhattan distance, because each table already includes its own tiles' Manhattan distances. It is also consistent: a move changes only one table's key, and that table's value changes by at most 1.
Costs and Design Decisions
| Decision | Effect | Typical choice |
|---|---|---|
| Pattern size | Bigger patterns give stronger h, but the table grows roughly as n!/(n−k)! | Largest size that fits in memory |
| Max vs. additive | Additive gives much larger values but requires disjoint patterns and the restricted cost model | Additive for tile puzzles |
| Storage | A Python dict is simple but costs dozens of bytes per entry | Array indexed by a permutation rank, 1 byte or 4 bits per entry |
| Pattern choice | Tiles that interact (same row or corner) capture more conflicts together | Group adjacent tiles |
For the 15-puzzle, the classic additive split is 7 + 8 tiles. The 8-tile table holds 16!/8! ≈ 519 million entries. If you store each entry in one byte at a dense index, that table needs about half a gigabyte. A dictionary of the same size would not fit in memory. In practice, you rank each placement to an integer index and use a flat byte array.
The common failure modes are:
- Overlapping patterns in an additive sum. Adding tables that share a tile can overestimate and break optimality.
- Using the full-cost PDB (all moves counted) in a sum. It is admissible alone but not when added.
- Forgetting that the abstract goal must match the concrete goal's layout, including where the blank ends up.
- Memory blowup from storing abstract states as tuples in a dictionary at 15-puzzle scale.
PDBs pair well with IDA. IDA uses little memory itself, which leaves room for large tables, and each lookup is constant time.
Exercise
You build two full-cost PDBs (every move costs 1) for the 8-puzzle, on patterns {1,2,3,4} and {5,6,7,8}, and use h = PDB1 + PDB2. Is h admissible? Explain.
Show answer
No, in general. Each full-cost table counts moves of wildcard tiles as well. A single concrete move of, say, tile 6 is counted in the first table as a wildcard move and in the second table as a pattern move. The sum can therefore exceed the true cost. Use max(PDB1, PDB2), or switch to the additive cost model, where only pattern tiles cost 1.
Exercise
In buildadditivepdb, why is the final table keyed by pattern-tile positions only, taking the minimum over blank positions? What would go wrong if you kept the blank in the key?
Show answer
Under the additive cost model, moving the blank among wildcards is free. This means the blank's position does not affect a placement's true additive cost. The minimum over blank positions is the correct lower bound and makes the table smaller. Keeping the blank in the key would still be admissible, but each table would be about (n−k) times larger. It would also be inconsistent with the other pattern's table, which assumes the blank can be anywhere.
Exercise
For the 15-puzzle (16 cells), how many entries does an additive PDB on 6 tiles need when keyed by tile positions only? How does that compare with keying the full-cost abstract state including the blank?
Show answer
Keyed by tile positions only, the table needs 16 × 15 × 14 × 13 × 12 × 11 = 5,765,760 entries. Including the blank multiplies that by the 10 remaining cells, giving 57,657,600 entries.