AI Wiki中文/EN

Pattern databases

模式数据库

Build exact abstract puzzle tables, expose double counting, and verify additive bounds on every solvable six-cell board.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Solve a smaller puzzle once, then reuse the answer

Arrange five numbered tiles and one empty square on a two-row, three-column board. A move slides a neighboring tile into the empty square. The goal is 1 2 3 / 4 5 0, where 0 denotes the empty square. How many moves remain from another arrangement?

One way to get a lower bound is to track only tiles 1 and 2 plus the empty square. The other tiles become indistinguishable, although they still occupy cells and can be moved. Precompute the minimum cost to put the tracked pieces in their goal positions for every abstract arrangement. That lookup table is a pattern database, or PDB.

Culberson and Schaeffer’s 1998 paper constructs such tables by retrograde search and combines several lower bounds with a maximum. Its first page identifies a 1996 conference predecessor. The table stores exact answers for an abstraction, rather than a prediction fitted from examples. Pattern Databases, first page and section 3

Here is a trap worth seeing before implementing one. Start just one move from the goal. Track disjoint groups (1,2), (3,4) and (5), always retaining the empty square. If every blank move costs one in every table, all three lookups return 1. Their sum is 3, although the real puzzle takes only one move.

One move cannot be charged three times

One move away

Goal

Tracked tilesUnit costsPartitioned
1, 210
3, 410
511
Sum3 · too high1 · bound
Every table retains the blank position. Unit-cost tables each charge for moving tile5. With cost partitioning, only the table tracking tile5 charges. Disjoint tile groups alone are insufficient.

The abstraction and its bill

Number cells 0 through 5 in row order. For pattern (1,2), encode an abstract state by the positions of the empty square, tile1 and tile2, in that order. For 1 2 3 / 4 0 5, the key is (4,0,1); at the goal it is (5,0,1). “Untracked” does not mean another empty square. There is still exactly one legal empty square.

Let ϕi(s)\phi_i(s) be the projection of a full board into pattern ii. Assign each abstract move a nonnegative cost cic_i. Exact distances to the abstract goal define

hi(s)=di(ϕi(s),ϕi(G)).h_i(s)=d_i\bigl(\phi_i(s),\phi_i(G)\bigr).

For an ordinary unit-cost table, every real move projects to a legal abstract move of cost1. Thus a full solution projects to an abstract solution of the same cost, whose optimum can only be smaller. Each table is a lower bound. Taking their maximum is safe; adding them might charge the same move repeatedly.

To make addition safe, distribute the cost of each real edge ee so that

ci(e)≥0,∑ici(e)≤c(e).c_i(e)\ge0,\qquad \sum_i c_i(e)\le c(e).

For our disjoint tile groups, charge1 only to the group containing the numbered tile that actually moves. All other groups charge0 for that move. Along any full solution path PP, each abstract optimum is no larger than its projected path cost. Summing gives

∑ihi(s)≤∑e∈P∑ici(e)≤∑e∈Pc(e).\sum_i h_i(s)\le\sum_{e\in P}\sum_i c_i(e)\le\sum_{e\in P}c(e).

Minimizing the right side over full solutions proves admissibility. The abstract shortest-path inequality also gives hi(s)≤ci(e)+hi(t)h_i(s)\le c_i(e)+h_i(t) on each real edge e:s→te:s\to t. Summing proves consistency of the additive bound. The actual cost allocation does the work; non-overlapping names alone do not.

Korf and Felner’s disjoint-PDB method counts only moves of tiles belonging to a group. Their implementation also removes the empty-square position from stored lookup keys. Our teaching version keeps that position and a fixed abstract goal in both table families, making the transition and cost comparison explicit. It therefore uses a different table representation. The linked manuscript is dated September5,2001; the journal article appeared in January2002. Author manuscript, sections 2.2–3, publisher record

Build both table families with one short program

This complete Python3.10+ example fixes the board shape, goal and three patterns. project is an internal helper for valid boards and patterns; lookup checks the full board. build_pdb checks tile labels and rejects empty or repeated patterns. Tables passed to lookup must be the three tables built for PATTERNS, in that order. This is a teaching interface, not a serialized database loader.

Move the empty square to an adjacent cell. If that cell contains a tracked tile, move the tracked tile into the old empty position. Otherwise only the empty-square coordinate changes. In partitioned mode the latter move costs0. Ordinary BFS counts edges and would solve the wrong cost problem for those 0/1 weights; Dijkstra handles both modes.

Our puzzle moves are reversible and their assigned costs are symmetric, so searching outward from the abstract goal computes costs back to it. A directed application would need reversed transitions with the appropriate original costs. Zero-cost cycles are harmless here: the abstract graph is finite and only strict distance improvements enter the heap.

from heapq import heappop, heappush
from math import inf

GOAL = (1, 2, 3, 4, 5, 0)
PATTERNS = ((1, 2), (3, 4), (5,))
NEIGHBORS = tuple(tuple(j for j in range(6)
                       if abs(i // 3 - j // 3) + abs(i % 3 - j % 3) == 1)
                  for i in range(6))


def project(board, pattern):
    # Internal helper: board is a permutation of 0..5; pattern has distinct 1..5.
    return tuple(board.index(tile) for tile in (0,) + pattern)


def abstract_edges(state, partitioned):
    # State stores the blank position, followed by each tracked tile position.
    blank = state[0]
    for destination in NEIGHBORS[blank]:
        positions = list(state)
        tracked = destination in state[1:]
        if tracked:
            positions[state.index(destination)] = blank
        positions[0] = destination
        cost = int(tracked) if partitioned else 1
        yield tuple(positions), cost


def build_pdb(pattern, partitioned=False):
    pattern = tuple(pattern)
    if (not pattern or any(type(t) is not int or not 1 <= t <= 5 for t in pattern)
            or len(set(pattern)) != len(pattern)):
        raise ValueError('pattern must contain distinct tiles from 1..5')
    if type(partitioned) is not bool:
        raise ValueError('partitioned must be boolean')
    target = project(GOAL, pattern)
    distance = {target: 0}
    heap = [(0, target)]
    while heap:
        d, state = heappop(heap)
        if d != distance[state]:
            continue
        # Puzzle transitions and their assigned costs are symmetric.
        for neighbor, cost in abstract_edges(state, partitioned):
            candidate = d + cost
            if candidate < distance.get(neighbor, inf):
                distance[neighbor] = candidate
                heappush(heap, (candidate, neighbor))
    return distance


def lookup(board, tables):
    if (len(board) != 6 or any(type(t) is not int for t in board)
            or set(board) != set(range(6))):
        raise ValueError('board must be a permutation of 0..5')
    return tuple(table[project(board, pattern)]
                 for pattern, table in zip(PATTERNS, tables, strict=True))


ordinary = tuple(build_pdb(p) for p in PATTERNS)
partitioned = tuple(build_pdb(p, True) for p in PATTERNS)
one_move = (1, 2, 3, 4, 0, 5)
assert tuple(map(len, ordinary)) == (120, 120, 30)
assert tuple(map(len, partitioned)) == (120, 120, 30)
assert lookup(one_move, ordinary) == (1, 1, 1)
assert lookup(one_move, partitioned) == (0, 0, 1)
assert lookup(GOAL, partitioned) == (0, 0, 0)
print('ordinary:', lookup(one_move, ordinary))
print('partitioned:', lookup(one_move, partitioned))

The output is (1,1,1) for ordinary costs and (0,0,1) for partitioned costs. Both modes contain 120,120 and30 entries. A pattern tracking kk numbered tiles plus the empty square has at most the following number of keys on NN cells:

Mk=N!(N−k−1)!.M_k=\frac{N!}{(N-k-1)!}.

For these patterns all possible keys are reached, so there are270 entries per family. An entry count is not a byte count: Python tuples, dictionaries and integers have overhead. Larger patterns retain more interactions but increase storage quickly.

For an abstract graph with ViV_i states and EiE_i transitions, the lazy-heap search uses O((Vi+Ei)log⁡(Vi+Ei+2))O((V_i+E_i)\log(V_i+E_i+2)) time and up to O(Vi+Ei)O(V_i+E_i) working storage, assuming fixed-size state keys. The retained distance table uses O(Vi)O(V_i) entries. On a growing board, key construction, hashing and comparisons also cost work; project scans the board once per tracked piece, O(N(k+1))O(N(k+1)) for this simple implementation. A position array can avoid repeated scans.

Check every solvable board, then compare bounds

The repository check independently generates legal full-board moves and performs BFS from the goal. It finds360 reachable boards among the720 permutations, with maximum optimal distance21. It checks every reachable board against both heuristics, and checks consistency on every legal edge. It also reconstructs abstract transitions from full permutations to check that the projection and cost allocation agree with actual tile moves.

These are results for our two-by-three puzzle and fixed groups, not a reproduction of the papers’ 15-puzzle benchmarks. Two examples show why the two table families should be compared by measurement:

BoardExactUnit maxSplit sum
4 1 3 / 2 5 0664
5 0 4 / 2 1 312810

The ordinary maximum is larger on241 reachable states, the partitioned sum on4, and they tie on115. Neither dominates the other. Addition is at least as large as the maximum of the same nonnegative partitioned tables; comparing it with ordinary tables changes the values as well as the combination rule. Since both finished heuristics are consistent lower bounds, taking the maximum of the ordinary maximum and partitioned sum is safe too, at the cost of storing and consulting both families.

1. Why is the first group’s partitioned lookup zero one move from the goal?

Answer: Tiles1 and2 are already placed. Moving tile5 puts the empty square at its target but charges nothing to group(1,2). A wrong full board can therefore have a zero value in one or several component tables.

2. If each tile belongs to only one group, may we sum ordinary PDB values?

Answer: No. Ordinary tables also charge for moving untracked tiles. In the one-move example, three disjoint groups still charge the same physical move three times. The per-move cost budget, rather than disjoint labels alone, establishes the sum bound.

3. What if one tile is accidentally included in two cost-one groups?

Answer: A move of that tile is charged twice. The stated cost-partition inequality fails, so this proof no longer guarantees admissibility. Repartition the groups or allocate costs whose sum per real move is at most one.

4. Can a finite lookup value prove that a full board is solvable?

Answer: No. An abstraction forgets constraints. For example, exchanging tiles1 and2 at the full goal produces an unreachable board in this puzzle, while these small pattern keys still have finite entries. An abstract solution need not lift to a real solution.

Precomputation has a price and a scope

For a single six-cell puzzle, solving the full graph may be simpler than building several tables. PDBs become useful when a stored abstraction helps many searches with the same rules and goal. Report build time, memory, lookup cost and search effort separately. A reduction in expanded nodes does not automatically pay back table construction or memory traffic.

An absent table key is not automatically a proof of an unreachable real goal. The database might be incomplete, have a different tile order, or belong to another goal. A practical file format needs board rules, goal, ordered pattern, move-cost convention, version and integrity checks. If construction is interrupted, do not present tentative distances as final lower bounds: a discovered path gives an upper bound on an abstract optimum until shortest-distance processing establishes otherwise.

Changing the goal, allowing diagonal moves, or changing move costs requires checking the abstraction again. A table based on the old rules can overestimate a newly cheaper solution. Compression must preserve a lower bound if optimality matters. Taking a minimum over merged entries can retain one; arbitrary rounding upward has no general guarantee.

Stored knowledge inside a search

Admissible heuristics gives the construction and composition rules used here. Uniform-cost search builds weighted tables. A* and IDA* can query them during search. PDBs demonstrate a concrete tradeoff between doing work before a query and retaining enough information to avoid repeating it. A complete solution database and a pattern database differ in what their keys remember, even when both are built backward from a goal.

Make a prediction, then check

One move of tile5 solves the puzzle,but three ordinary tables each return1.Can they be directly summed?

Choose one answer

Learning objectives

  • Build blank-aware abstract transitions,distinguish unit and partitioned costs,and prove additive bounds.
  • Use full six-cell enumeration to check entries,unsolvable counterexamples and lack of dominance between the two combinations.

Prerequisites & connections

Explore related knowledge →

References

  1. Pattern Databases
    Joseph C. Culberson; Jonathan Schaeffer · 1998
  2. Disjoint Pattern Database Heuristics — author manuscript dated2001-09-05
    Richard E. Korf; Ariel Felner · 2001
  3. Disjoint pattern database heuristics — publication record
    Richard E. Korf; Ariel Felner · 2002

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check:primary source locations,independent finite-graph and complete six-cell puzzle oracles,executed examples and bilingual comparison;no independent human peer review.

  • Reread both languages for blank identity,fixed goals,0/1costs,unit-table counterexample,additive and consistency proofs,270entries,360states,dominance counterexamples,complexity and incomplete-build risks.
  • Ran7new independent tests:729nonnegative three-vertex graphs with16estimates each versus Floyd;full-permutation projections and Bellman table oracles;all360reachable boards and their edges.
  • Structural comparison confirms paired code,display equations,six section anchors and four answered exercises.No independent human peer review.

Source locations checked:

  • Pattern Databases · Read PDF1,4–5:first-page1996predecessor note and§3distinguishing unspecified tiles from the actual blank,retrograde costs,lower-bound lemma and maximum lookup. No benchmark speed claims reproduced.
  • Disjoint Pattern Database Heuristics — author manuscript dated2001-09-05 · Read PDF5–9,§2.2–3:ordinary moves charge untracked tiles;cost partition counts moves of group tiles. Manuscript drops blank from final stored key;article explicitly retains it and fixed target as a distinct teaching implementation.
  • Disjoint pattern database heuristics — publication record · Publisher search result gives January2002,volume134issues1–2,pages9–22,DOI10.1016/S0004-3702(01)00092-3;manuscript title page explicitly dated September5,2001.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.