Module contents
Lesson 3 of 23Advanced 95 min

Heuristic search at scale: linear memory, bounded suboptimality and pattern databases

A* runs out of memory long before time. Study specialist responses: linear-memory IDA* and RBFS, weighted A* and anytime search with suboptimality guarantees, and abstraction-based precomputed heuristics (additive pattern databases) that solve the 15-puzzle and Rubik’s cube optimally.

After this lesson you can

  • Implement IDA* and analyze its iteration count with integer and real costs.
  • Prove the w·C* bound for weighted A* and use ARA* to obtain anytime solutions.
  • Build pattern databases by backward search in an abstraction and index them by permutation ranking.
  • Combine disjoint PDBs additively while preserving admissibility.
  • Choose between linear memory, bounded suboptimality and precomputed heuristics for available resources.

Before you start

The memory wall

A* with a consistent heuristic is optimal and, among algorithms using the same information, expands nothing it does not have to. Its problem is memory rather than time: it stores every node it generates because it needs them to detect duplicates and reconstruct the path. In a real problem the node table grows with the clock, and memory runs out long before patience.

The 15-puzzle makes this tangible. It has 16!/2≈1.05×101316!/2 \approx 1.05\times 10^{13} reachable states, and a random instance requires 52.552 moves on average. Felner, Korf and Hanan (2004) measured that IDA* with Manhattan distance generates 401 189 630 nodes on average to solve a random instance (1000 instances). A* would save repeated nodes, but would have to store every distinct state it generates at once. The next cell measures the storage cost in Python: it runs A* with Manhattan on a hard instance, stops at 20 000 expansions and measures memory with tracemalloc.

[ ]The memory wallBrowser
import heapq, random, time, tracemalloc

# 15-puzzle: casillas 0..15 fila a fila; la ficha t va en la casilla t y el hueco (0) arriba a la izquierda
NBRS = [[q for q, ok in ((p - 4, p >= 4), (p + 4, p < 12), (p - 1, p % 4 > 0), (p + 1, p % 4 < 3)) if ok] for p in range(16)]
MD = [[abs(p // 4 - t // 4) + abs(p % 4 - t % 4) for t in range(16)] for p in range(16)]
META = tuple(range(16))

def manhattan(s):
    return sum(MD[p][t] for p, t in enumerate(s) if t)

def paseo(n, semilla):
    """Estado a n movimientos aleatorios de la meta (sin deshacer el anterior)."""
    rng = random.Random(semilla)
    s, b, prev = list(META), 0, -1
    for _ in range(n):
        q = rng.choice([q for q in NBRS[b] if q != prev])
        s[b], s[q] = s[q], 0
        prev, b = b, q
    return tuple(s)

def astar_hasta(s0, max_exp):
    """A* con Manhattan, cortado tras max_exp expansiones. Devuelve (expandidos, estados guardados)."""
    g = {s0: 0}
    abiertos = [(manhattan(s0), 0, s0)]
    cerrados = set()
    while abiertos and len(cerrados) < max_exp:
        _, _, s = heapq.heappop(abiertos)
        if s in cerrados:
            continue
        cerrados.add(s)
        b = s.index(0)
        for q in NBRS[b]:
            l = list(s)
            l[b], l[q] = l[q], 0
            c = tuple(l)
            if g[s] + 1 < g.get(c, 1 << 30):
                g[c] = g[s] + 1
                heapq.heappush(abiertos, (g[c] + manhattan(c), -g[c], c))
    return len(cerrados), len(g)

def ida_hasta(s0, max_gen):
    """IDA* con Manhattan sobre un único tablero que se modifica en el sitio, cortado tras max_gen nodos."""
    s = list(s0)
    gen = prof_max = 0
    def dfs(b, g, umbral, prev):
        nonlocal gen, prof_max
        prof_max = max(prof_max, g)
        f = g + manhattan(s)
        if f > umbral or gen >= max_gen:
            return f
        minimo = 1 << 30
        for q in NBRS[b]:
            if q == prev:
                continue
            gen += 1
            s[b], s[q] = s[q], 0
            minimo = min(minimo, dfs(q, g + 1, umbral, b))
            s[q], s[b] = s[b], 0
        return minimo
    umbral = manhattan(s0)
    while gen < max_gen:
        umbral = dfs(s.index(0), 0, umbral, -1)
    return gen, prof_max

s0 = paseo(400, 7)
print("instancia:", s0, "  Manhattan:", manhattan(s0))

t = time.perf_counter()
exp, guardados = astar_hasta(s0, 20000)
dt = time.perf_counter() - t
tracemalloc.start()
astar_hasta(s0, 20000)
pico_astar = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
por_estado = pico_astar / guardados
print(f"A*:   {exp} expansiones, {guardados} estados guardados ({guardados / exp:.2f} por expansión)")
print(f"      memoria pico {pico_astar / 1e6:.1f} MB = {por_estado:.0f} bytes por estado guardado")
print(f"      ritmo: {exp / dt:,.0f} expansiones/s  ->  {exp / dt * guardados / exp * por_estado / 1e6:.1f} MB/s")
print(f"      8 GB se llenarían en {8e9 / (exp / dt * guardados / exp * por_estado) / 60:.0f} minutos")

gen, prof = ida_hasta(s0, 60000)
print(f"IDA*: {gen} nodos generados guardando a la vez como mucho {prof + 1} estados (el camino actual)")

A* stores around 1.9 states per expansion and each costs on the order of 160 bytes in Python (the tuple, the cost-dictionary entry and the heap entry). At its rate, tens of MB per second, 8 GB runs out in minutes while the instance is still far from solved. A C program uses fewer bytes per node but also generates nodes tens of times faster (Felner, Korf and Hanan measured 7.5 million nodes per second with Manhattan on a 500 MHz PC): memory runs out just as soon. IDA*, in contrast, traverses the same nodes while storing only its current path, a few dozen states.

This lesson studies three responses to the wall, which can be combined:

  1. Linear memory. IDA* and RBFS search depth-first with the same guarantee as A*, paying in time for what they save in memory.
  2. Bounded suboptimality. Weighted A* and ARA* accept a worse solution with a provable bound on how much worse, in exchange for orders of magnitude fewer expanded nodes.
  3. Precomputed heuristics. Pattern databases spend memory once, before searching, to make the heuristic good enough for search to fit any budget.

IDA*: iterative deepening over f

Iterative deepening repeated depth-first searches with an increasing depth limit. IDA* (Korf, 1985) does the same with a limit on f=g+hf = g + h.

Each iteration is pure depth-first search: memory is the current path, O(d)\bigO(d) states, or O(bd)\bigO(bd) if siblings are stored for iteration. Choosing the smallest pruned ff as the next threshold gives optimality.

Proof

First, thresholds never exceed C∗C^*. Let PP be an optimal path. While θi<C∗\theta_i < C^*, the goal at the end of PP has f=C∗>θif = C^* > \theta_i, so some node of PP is pruned in iteration ii: the first on PP with f>θif > \theta_i (all previous ones have f≤θif \le \theta_i and are expanded). Since hh is admissible, that node nn has f(n)=g∗(n)+h(n)≤g∗(n)+h∗(n)=C∗f(n) = g^*(n) + h(n) \le g^*(n) + h^*(n) = C^*, so θi+1≤f(n)≤C∗\theta_{i+1} \le f(n) \le C^*.

Second, thresholds strictly increase and every iteration is finite: with threshold θ\theta, no path with more than θ/ε\theta/\eps edges has g≤θg \le \theta, and finite branching gives only finitely many such paths. Between h(s0)h(s_0) and C∗C^* there are only finitely many ff values reachable by paths of cost ≤C∗\le C^*, so after finitely many iterations θi=C∗\theta_i = C^* (or a goal with f≤θi<C∗f \le \theta_i < C^* is found earlier, impossible because every goal has f=g≥C∗f = g \ge C^*).

Finally, in the iteration with θi=C∗\theta_i = C^* all nodes on PP have f≤C∗f \le C^* and none is pruned, so depth-first search reaches a goal. The first it visits has g=f≤C∗g = f \le C^*, hence cost exactly C∗C^*.

∎

Memory is linear, but time depends on how many iterations there are and how much each grows relative to the previous one. The figure shows both in a toy tree.

InteractiveIDA* thresholds
232332341223132243221S: g = 0, h = 4, f = 44SA: g = 2, h = 4, f = 66A1: g = 5, h = 3, f = 88A1a: g = 7, h = 2, f = 99G′: g = 10, h = 0, f = 1010G′A1b: g = 8, h = 1, f = 99A2: g = 4, h = 4, f = 88A2a: g = 7, h = 3, f = 1010A2b: g = 8, h = 2, f = 1010B: g = 1, h = 5, f = 66B1: g = 3, h = 4, f = 77B1a: g = 5, h = 4, f = 99B1b: g = 6, h = 3, f = 99B2: g = 2, h = 6, f = 88B2a: g = 5, h = 5, f = 1010C: g = 2, h = 3, f = 55C1: g = 4, h = 4, f = 88C1a: g = 8, h = 2, f = 1010C2: g = 5, h = 2, f = 77C2a: g = 7, h = 2, f = 99G∗: g = 9, h = 0, f = 99G∗C2b: g = 6, h = 3, f = 9945678910thresholdC*
nodes generated each iteration (select a bar to go there)
  • expanded: f≤f \le threshold
  • generated and pruned: f>f > threshold
  • not generated this iteration
Edge costs
0.00
iteration 1 of 6
Threshold this iteration4
Next threshold5
Nodes generated this iteration4
Cumulative generated by IDA*4 (total 75)
Generated by A* in this tree21
Distinct f≤C∗f \le C^* values6
Cost found / C∗C^*9 / 9
6 iterations reach C∗=9C^* = 9. IDA generates 75 nodes versus 21 for A, storing only the current path. In a small tree repetition matters; with high branching, the final iteration dominates.
A tree of 22 nodes with admissible hh; each node shows its f=g+hf = g + h. Optimal goal G∗ costs C∗=9C^* = 9 and goal G′, farther left, costs 10. Each player step is one iteration: expanded nodes are blue (f≤f \le threshold), generated and pruned nodes have dashed orange borders, and the pruned node with smallest ff, setting the next threshold, has a thick orange border. The lower bar places all tree ff values on a line, with the current threshold, the next (dashed) and C∗C^*. Integer costs give 6 iterations; switch to real costs (each edge gets 0.02 to 0.24 more expensive) and count them. Then increase δ\delta: when does IDA∗ stop returning G∗?

How many iterations

With integer costs and integer hh, all ff values are integers, so the thresholds are distinct integers between h(s0)h(s_0) and C∗C^*:

#iteraciones≤C∗−h(s0)+1.\#\text{iteraciones} \le C^* - h(s_0) + 1.

In the figure’s tree there are exactly 9−4+1=69 - 4 + 1 = 6. In the 15-puzzle with Manhattan the count is better still: each move changes gg by 1 and the moved tile’s Manhattan distance by ±1\pm 1, so ff changes by 0 or 2 and preserves parity. Thresholds advance by two and there are at most (C∗−h(s0))/2+1(C^* - h(s_0))/2 + 1 iterations.

Total time is controlled too. If the number of nodes with f≤θf \le \theta grows geometrically with the threshold, by ratio β>1\beta > 1 per iteration, the final iteration dominates and all earlier ones together cost at most a fraction 1/(β−1)1/(\beta - 1) of it: the same argument that made iterative deepening cheap. Korf (1997) observed for Rubik’s cube that this ratio between consecutive iterations is very stable and approximately the search tree’s branching factor, 13.34847: repeating previous iterations adds only 8%, which is 1/(β−1)1/(\beta - 1) with that β\beta.

Real costs: the worst case

The preceding argument breaks down with real costs. If almost no two nodes have the same ff, each iteration raises the threshold just to the next ff and adds one or very few new nodes. In the worst case, if A* expands NN nodes with distinct ff, IDA* performs NN iterations and the ii-th expands ii nodes: N(N+1)/2=O(N2)N(N+1)/2 = \bigO(N^2) expansions in total, versus A*‘s NN. In the figure’s tree, real costs yield 16 distinct f≤C∗f \le C^* values and 16 iterations.

The next cell measures this on the 8-puzzle with two cost sets: all moves cost 1, or moving tile tt costs ct=1+0.5⋅frac⁡(tφ)c_t = 1 + 0.5\cdot\operatorname{frac}(t\varphi), a different number between 1 and 1.5 for each tile. The heuristic is h(s)=∑tct MDt(s)h(s) = \sum_t c_t\,\mathrm{MD}_t(s), admissible because each tile must move at least its Manhattan distance and each move costs ctc_t.

[ ]IDA* from scratch, with integer and real costsBrowser
import math

def ida_star(s0, h, sucesores, es_meta, delta=0.0):
    """IDA* genérico. sucesores(s) -> [(hijo, coste)]. El umbral siguiente es max(menor f podado, umbral + delta)."""
    camino = [s0]
    st = {"generados": 1, "iteraciones": 0, "umbrales": []}
    def dfs(g, umbral):
        s = camino[-1]
        f = g + h(s)
        if f > umbral + 1e-12:
            return f
        if es_meta(s):
            return -1.0                          # señal de éxito (las f nunca son negativas)
        minimo = math.inf
        for c, coste in sucesores(s):
            if len(camino) > 1 and c == camino[-2]:
                continue                         # no deshacer el último movimiento
            st["generados"] += 1
            camino.append(c)
            r = dfs(g + coste, umbral)
            if r == -1.0:
                return r
            camino.pop()
            minimo = min(minimo, r)
        return minimo
    umbral = h(s0)
    while True:
        st["iteraciones"] += 1
        st["umbrales"].append(umbral)
        r = dfs(0.0, umbral)
        if r == -1.0:
            return list(camino), st
        if r == math.inf:
            return None, st
        umbral = max(r, umbral + delta)

# 8-puzzle con el hueco arriba a la izquierda; mover la ficha t cuesta c[t]
N3 = [[q for q, ok in ((p - 3, p >= 3), (p + 3, p < 6), (p - 1, p % 3 > 0), (p + 1, p % 3 < 2)) if ok] for p in range(9)]
MD3 = [[abs(p // 3 - t // 3) + abs(p % 3 - t % 3) for t in range(9)] for p in range(9)]

def puzzle8(costes):
    def suc(s):
        b = s.index(0)
        out = []
        for q in N3[b]:
            l = list(s)
            l[b], l[q] = l[q], 0
            out.append((tuple(l), costes[s[q]]))
        return out
    h = lambda s: sum(costes[t] * MD3[p][t] for p, t in enumerate(s) if t)   # admisible: cada ficha se mueve >= MD veces
    return suc, h

def coste_camino(camino, costes):
    return sum(costes[a[b.index(0)]] for a, b in zip(camino, camino[1:]))

s8 = (8, 6, 7, 2, 5, 4, 3, 0, 1)
enteros = [0] + [1] * 8
phi = (1 + 5 ** 0.5) / 2
reales = [0] + [1 + 0.5 * ((t * phi) % 1) for t in range(1, 9)]   # entre 1 y 1.5, sin empates
es_meta = lambda s: s == tuple(range(9))

for nombre, c in (("enteros", enteros), ("reales", reales)):
    suc, h = puzzle8(c)
    camino, st = ida_star(s8, h, suc, es_meta)
    print(f"costes {nombre:8s}: h(s0) = {h(s8):6.3f}, C* = {coste_camino(camino, c):7.3f} ({len(camino) - 1} movimientos), "
          f"{st['iteraciones']:3d} iteraciones, {st['generados']:8,d} nodos")
    print("   primeros umbrales:", [round(u, 3) for u in st["umbrales"][:6]])

With unit costs, h(s0)=19h(s_0) = 19 and C∗=27C^* = 27: thresholds are 19,21,23,25,2719, 21, 23, 25, 27, five iterations, exactly (27−19)/2+1(27 - 19)/2 + 1. With real costs the optimal solution still has 27 moves, but IDA* needs 45 iterations and generates 13 times more nodes (150 541 versus 11 598). Thresholds advance in hundredths.

The remedy: minimum threshold jumps

If losing a little quality is acceptable, the solution is to force the threshold to increase by at least δ\delta each iteration:

θi+1=max⁡(min⁡{f(n):f(n)>θi}, θi+δ).\theta_{i+1} = \max\big(\min\{f(n) : f(n) > \theta_i\},\ \theta_i + \delta\big).
Proof

Let θk\theta_k be the threshold of the iteration finding the goal. The visited goal has h=0h = 0, hence C=f≤θkC = f \le \theta_k. If k=0k = 0, θ0=h(s0)≤C∗\theta_0 = h(s_0) \le C^* and we are done. Otherwise, iteration k−1k - 1 found no goal, which by the preceding proof’s argument implies θk−1<C∗\theta_{k-1} < C^* (with θk−1≥C∗\theta_{k-1} \ge C^* the entire optimal path has f≤C∗f \le C^* and none of it is pruned) and that the smallest pruned ff is ≤C∗\le C^*. Therefore θk=max⁡(menor f podado, θk−1+δ)≤max⁡(C∗, C∗+δ)=C∗+δ\theta_k = \max(\text{menor } f \text{ podado},\ \theta_{k-1} + \delta) \le \max(C^*,\ C^* + \delta) = C^* + \delta.

∎
[ ]The fixed-jump remedyBrowser
suc, h = puzzle8(reales)
c_opt = None
print(" delta  iteraciones     nodos     coste   cota C*+delta")
for d in (0.0, 0.1, 0.25, 0.5, 1.0, 2.0, 4.0):
    camino, st = ida_star(s8, h, suc, es_meta, delta=d)
    c = coste_camino(camino, reales)
    c_opt = c if d == 0 else c_opt
    print(f"{d:6.2f} {st['iteraciones']:11d} {st['generados']:10,d} {c:9.3f} {c_opt + d:12.3f}")

With δ=0.5\delta = 0.5, iterations fall from 45 to 16 and nodes from 150 541 to 31 480, while the solution remains optimal. This is typical: bound C∗+δC^* + \delta is a worst case, and depth-first search returns a worse solution only if it encounters that one before the optimum in the last iteration. Here that occurs with δ=4\delta = 4: cost 36.408, within the 38.318 bound. More refined variants choose the next threshold from the distribution of pruned ff values so each iteration grows by a preset factor, such as IDA*_CR (Sarkar, Chakrabarti, Ghose and De Sarkar, 1991).

The weakness: transpositions

IDA* does not remember which states it has seen. In a tree that makes no difference, but in a graph with many distinct paths to the same state (transpositions), each path is explored separately. Removing the inverse move, as the preceding cells do, eliminates length-2 cycles but not equivalent paths: on a grid, going two right and one down reaches the same place by three paths.

[ ]Transpositions: IDA* on a gridBrowser
def rejilla(ancho, alto, muro):
    """Rejilla 4-conexa con un muro vertical en la columna ancho//2 (hueco solo en la fila de abajo)."""
    libre = {(x, y) for x in range(ancho) for y in range(alto) if not (x == ancho // 2 and y < alto - 1 and muro)}
    def suc(p):
        x, y = p
        return [((x + dx, y + dy), 1) for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)) if (x + dx, y + dy) in libre]
    return libre, suc

for n in (5, 6, 7, 8):
    libre, suc = rejilla(n, n, True)
    meta = (n - 1, 0)
    h = lambda p, meta=meta: abs(p[0] - meta[0]) + abs(p[1] - meta[1])
    camino, st = ida_star((0, 0), h, suc, lambda p, meta=meta: p == meta)
    print(f"rejilla {n}x{n}: {len(libre):3d} casillas, C* = {len(camino) - 1:2d}, "
          f"IDA* genera {st['generados']:10,d} nodos en {st['iteraciones']} iteraciones (A* expande como mucho {len(libre)})")

With 57 cells, IDA* generates 206 149 nodes: the wall forces it down to the last row, Manhattan does not know this, and every iteration enumerates all equivalent paths up to the threshold. A* expands at most 57. That is why IDA* shines on the 15-puzzle and Rubik’s cube, whose graphs resemble trees when undoing moves are forbidden, and fails on grid maps, where graph search with a state table is indispensable (you can add a bounded transposition table, as in game engines).

RBFS and SMA*: remembering the best alternative

IDA* forgets everything between iterations. Recursive best-first search (Korf, 1993) keeps a little more information while retaining linear memory.

With admissible hh, RBFS is optimal (Korf, 1993). Its cost is changing its mind: when it abandons a branch for a better one and later returns, it regenerates the entire branch. With real costs it has the same problem as IDA*: if ff ties are rare, each change advances little and regenerations multiply.

[ ]RBFS versus IDA* and A*Browser
def rbfs(s0, h, sucesores, es_meta):
    """Recursive best-first search (Korf 1993). Memoria: los hermanos de cada nodo del camino actual."""
    st = {"generados": 1, "guardados_max": 0, "expansiones": 0}
    guardados = [0]
    def rec(camino, g, F, limite):
        s = camino[-1]
        if es_meta(s):
            return list(camino), F
        st["expansiones"] += 1
        hijos = []
        for c, coste in sucesores(s):
            if len(camino) > 1 and c == camino[-2]:
                continue
            st["generados"] += 1
            # el hijo hereda el valor respaldado del padre si este ya se había explorado (F > f)
            hijos.append([max(g + coste + h(c), F), g + coste, c])
        if not hijos:
            return None, math.inf
        guardados[0] += len(hijos)
        st["guardados_max"] = max(st["guardados_max"], guardados[0])
        while True:
            hijos.sort(key=lambda x: x[0])
            mejor = hijos[0]
            if mejor[0] > limite:
                guardados[0] -= len(hijos)
                return None, mejor[0]
            alternativa = hijos[1][0] if len(hijos) > 1 else math.inf
            camino.append(mejor[2])
            res, mejor[0] = rec(camino, mejor[1], mejor[0], min(limite, alternativa))
            camino.pop()
            if res is not None:
                guardados[0] -= len(hijos)
                return res, mejor[0]
    camino, _ = rec([s0], 0.0, h(s0), math.inf)
    return camino, st

def astar(s0, h, sucesores, es_meta):
    g = {s0: 0.0}
    padre = {s0: None}
    abiertos = [(h(s0), 0.0, 0, s0)]
    cerrados = set()
    n = 0
    while abiertos:
        _, ng, _, s = heapq.heappop(abiertos)
        gs = -ng
        if s in cerrados:
            continue
        if es_meta(s):
            camino = []
            while s is not None:
                camino.append(s)
                s = padre[s]
            return camino[::-1], {"generados": len(g), "guardados_max": len(g)}
        cerrados.add(s)
        for c, coste in sucesores(s):
            if gs + coste < g.get(c, math.inf):
                g[c] = gs + coste
                padre[c] = s
                n += 1
                heapq.heappush(abiertos, (g[c] + h(c), -g[c], n, c))

suc, h = puzzle8(enteros)
print("instancia             C*  |  A*: generados  guardados  |  IDA*: generados  |  RBFS: generados  guardados")
for semilla in range(5):
    rng = random.Random(semilla)
    s, b, prev = list(range(9)), 0, -1
    for _ in range(60):
        q = rng.choice([q for q in N3[b] if q != prev])
        s[b], s[q] = s[q], 0
        prev, b = b, q
    s = tuple(s)
    ca, sa = astar(s, h, suc, es_meta)
    ci, si = ida_star(s, h, suc, es_meta)
    cr, sr = rbfs(s, h, suc, es_meta)
    assert len(ca) == len(ci) == len(cr)
    print(f"{''.join(map(str, s))}  {len(ca) - 1:3d}  | {sa['generados']:14,d} {sa['guardados_max']:10,d} |"
          f" {si['generados']:15,d}  | {sr['generados']:15,d} {sr['guardados_max']:9d}")

All three find the same cost (the assertion checks it). A* stores hundreds of states; RBFS, a few dozen, on the order of bb per level. In generated nodes RBFS falls between A* and IDA* on three of five instances, but not always: on the second (5628 versus 2203) and fourth (2105 versus 1957), its changes of mind cost more than IDA*‘s iterations.

IDA* and RBFS share the problem that they use too little memory: even with gigabytes free, they cannot exploit them. SMA* (simplified memory-bounded A*, Russell, 1992) is A* with a node cap: when memory fills, it discards the leaf with largest ff and backs up its value to the parent, regenerating it only if everything else proves worse. It is complete if the path to the shallowest goal fits in available memory, and optimal if a path to some optimal solution fits; otherwise it returns the best solution it can reach with that memory. It degrades gracefully: with abundant memory it behaves like A*, and with little, like a search that regenerates often.

Weighted A*: the price of haste

The second response to the wall is to give up optimality, but in a controlled way. Pohl (1970) proposed inflating the heuristic.

By weighting hh more heavily, search prefers nodes that appear close to the goal even if they were costly to reach, and plunges deep along the path indicated by the heuristic. Surprisingly, quality is not lost without bound.

Proof

Let P=(s0=n0,n1,…,nk)P = (s_0 = n_0, n_1, \dots, n_k) be an optimal path. Lemma: while WA* has not terminated, some njn_j on PP is in OPEN with g(nj)=g∗(nj)g(n_j) = g^*(n_j). If s0s_0 is in OPEN, j=0j = 0 suffices. Otherwise let jj be the largest index such that njn_j has been expanded with g(nj)=g∗(nj)g(n_j) = g^*(n_j); on expansion nj+1n_{j+1} received g(nj+1)=g∗(nj+1)g(n_{j+1}) = g^*(n_{j+1}) (it cannot be smaller) and entered or returned to OPEN, because closed nodes are reopened. By maximality of jj, nj+1n_{j+1} has not since been expanded with that gg, so remains in OPEN.

When WA* selects a goal GG to expand, it has the smallest fwf_w in OPEN. Using the lemma’s njn_j and h(G)=0h(G) = 0,

C=g(G)=fw(G)≤fw(nj)=g∗(nj)+w h(nj)≤w g∗(nj)+w h∗(nj)=w C∗,C = g(G) = f_w(G) \le f_w(n_j) = g^*(n_j) + w\,h(n_j) \le w\,g^*(n_j) + w\,h^*(n_j) = w\,C^*,

where w≥1w \ge 1 is used in the first term, admissibility h(nj)≤h∗(nj)h(n_j) \le h^*(n_j) in the second, and njn_j lies on an optimal path, g∗(nj)+h∗(nj)=C∗g^*(n_j) + h^*(n_j) = C^*. Termination follows as in A*: OPEN’s fwf_w values cannot remain below w C∗w\,C^* indefinitely with costs ≥ε\ge \eps and finite branching.

∎

In practice almost nobody reopens: if hh is consistent, WA* without reopening closed nodes still satisfies C≤w C∗C \le w\,C^* (Likhachev, Gordon and Thrun prove this in the ARA* paper, 2003), avoiding re-expansions. This is the version used in the next figure.

InteractiveThe price of haste: weighted A*
1.01.21.41.61.82.0100100010⁴10⁵10⁶expanded nodes (log scale)cost / C*bound: cost ≤ 2.00·C*C* = 39, cost 41, 2797 expanded nodesC* = 36, cost 40, 638 expanded nodesC* = 34, cost 44, 4094 expanded nodesC* = 40, cost 46, 1639 expanded nodesC* = 39, cost 45, 6074 expanded nodesC* = 25, cost 29, 184 expanded nodesC* = 33, cost 43, 207 expanded nodesC* = 43, cost 45, 44068 expanded nodesC* = 31, cost 35, 7352 expanded nodesC* = 39, cost 47, 6107 expanded nodesC* = 44, cost 58, 4656 expanded nodesC* = 40, cost 42, 3799 expanded nodesC* = 40, cost 48, 836 expanded nodesC* = 19, cost 19, 175 expanded nodesC* = 41, cost 49, 7454 expanded nodesC* = 43, cost 47, 772 expanded nodesC* = 40, cost 48, 5474 expanded nodesC* = 34, cost 34, 578 expanded nodesC* = 37, cost 45, 3212 expanded nodesC* = 32, cost 34, 10386 expanded nodesC* = 31, cost 33, 6216 expanded nodesC* = 38, cost 42, 12621 expanded nodesC* = 38, cost 46, 9044 expanded nodesC* = 36, cost 46, 2140 expanded nodesC* = 30, cost 36, 269 expanded nodesC* = 26, cost 32, 1049 expanded nodesC* = 39, cost 47, 16836 expanded nodesC* = 33, cost 39, 655 expanded nodesC* = 39, cost 49, 615 expanded nodesC* = 28, cost 32, 2204 expanded nodesC* = 37, cost 43, 5431 expanded nodesC* = 38, cost 46, 26309 expanded nodesC* = 36, cost 46, 770 expanded nodesC* = 37, cost 45, 796 expanded nodesC* = 34, cost 42, 1618 expanded nodesC* = 42, cost 46, 10804 expanded nodesC* = 37, cost 39, 767 expanded nodesC* = 37, cost 37, 5173 expanded nodesC* = 36, cost 40, 1413 expanded nodesC* = 39, cost 51, 2968 expanded nodesC* = 35, cost 45, 11522 expanded nodesC* = 39, cost 41, 3803 expanded nodesC* = 33, cost 39, 3251 expanded nodesC* = 30, cost 36, 360 expanded nodesC* = 31, cost 35, 482 expanded nodesC* = 44, cost 44, 7655 expanded nodesC* = 39, cost 47, 6460 expanded nodesC* = 34, cost 40, 5018 expanded nodesC* = 38, cost 38, 644 expanded nodesC* = 35, cost 37, 4337 expanded nodesC* = 17, cost 17, 603 expanded nodesC* = 35, cost 37, 4098 expanded nodesC* = 29, cost 41, 4444 expanded nodesC* = 36, cost 40, 485 expanded nodesC* = 45, cost 53, 18300 expanded nodesC* = 30, cost 34, 275 expanded nodesC* = 34, cost 36, 3775 expanded nodesC* = 33, cost 35, 7103 expanded nodesC* = 35, cost 43, 435 expanded nodesC* = 34, cost 38, 2742 expanded nodesC* = 39, cost 39, 1193 expanded nodesC* = 35, cost 43, 11094 expanded nodesC* = 39, cost 41, 62899 expanded nodesC* = 49, cost 57, 43430 expanded nodesC* = 31, cost 37, 2468 expanded nodesC* = 27, cost 29, 772 expanded nodesC* = 45, cost 57, 31203 expanded nodesC* = 37, cost 47, 9226 expanded nodesC* = 36, cost 50, 10956 expanded nodesC* = 38, cost 46, 1769 expanded nodesC* = 34, cost 38, 24598 expanded nodesC* = 34, cost 40, 7664 expanded nodesC* = 41, cost 43, 65087 expanded nodesC* = 34, cost 38, 194 expanded nodesC* = 29, cost 41, 21551 expanded nodesC* = 46, cost 52, 17033 expanded nodesC* = 40, cost 56, 4682 expanded nodesC* = 33, cost 35, 1378 expanded nodesC* = 29, cost 33, 1213 expanded nodesC* = 32, cost 38, 3129 expanded nodesC* = 38, cost 38, 859 expanded nodesC* = 39, cost 47, 7909 expanded nodesC* = 32, cost 32, 5914 expanded nodesC* = 42, cost 54, 2729 expanded nodesC* = 47, cost 53, 13257 expanded nodesC* = 28, cost 28, 752 expanded nodesC* = 27, cost 29, 630 expanded nodesC* = 25, cost 27, 254 expanded nodesC* = 36, cost 36, 5002 expanded nodesC* = 29, cost 29, 1666 expanded nodesC* = 27, cost 31, 369 expanded nodesC* = 32, cost 38, 9648 expanded nodesC* = 41, cost 47, 21780 expanded nodesC* = 34, cost 40, 6390 expanded nodesC* = 22, cost 22, 250 expanded nodesC* = 38, cost 42, 25971 expanded nodesC* = 41, cost 49, 3754 expanded nodesC* = 45, cost 53, 3899 expanded nodesC* = 41, cost 45, 11001 expanded nodesC* = 38, cost 44, 26008 expanded nodesC* = 35, cost 43, 5375 expanded nodesC* = 34, cost 40, 14932 expanded nodesC* = 42, cost 44, 7731 expanded nodesC* = 38, cost 42, 18651 expanded nodesC* = 19, cost 27, 98 expanded nodesC* = 39, cost 55, 5334 expanded nodesC* = 44, cost 54, 10371 expanded nodesC* = 38, cost 50, 21506 expanded nodesC* = 35, cost 47, 4998 expanded nodesC* = 41, cost 43, 9232 expanded nodesC* = 38, cost 44, 4863 expanded nodesC* = 32, cost 32, 349 expanded nodesC* = 40, cost 40, 5529 expanded nodesC* = 35, cost 39, 1578 expanded nodesC* = 30, cost 32, 6386 expanded nodesC* = 30, cost 30, 160 expanded nodesC* = 33, cost 39, 2002 expanded nodesC* = 16, cost 16, 29 expanded nodesC* = 34, cost 40, 3580 expanded nodesC* = 45, cost 59, 47157 expanded nodesC* = 36, cost 40, 11138 expanded nodesC* = 43, cost 53, 20751 expanded nodesC* = 46, cost 52, 22947 expanded nodesC* = 41, cost 45, 3764 expanded nodesC* = 36, cost 42, 31465 expanded nodesC* = 32, cost 34, 4189 expanded nodesC* = 35, cost 43, 84046 expanded nodesC* = 37, cost 45, 5697 expanded nodesC* = 35, cost 39, 12398 expanded nodesC* = 26, cost 36, 8339 expanded nodesC* = 34, cost 42, 5147 expanded nodesC* = 31, cost 37, 2816 expanded nodesC* = 40, cost 46, 9209 expanded nodesC* = 42, cost 50, 40456 expanded nodesC* = 30, cost 32, 5705 expanded nodesC* = 39, cost 47, 26318 expanded nodesC* = 45, cost 51, 16885 expanded nodesC* = 39, cost 43, 83409 expanded nodesC* = 31, cost 37, 546 expanded nodesC* = 34, cost 44, 1241 expanded nodesC* = 32, cost 38, 352 expanded nodesC* = 38, cost 48, 5407 expanded nodesC* = 35, cost 37, 15520 expanded nodesC* = 42, cost 50, 22392 expanded nodesC* = 37, cost 45, 38004 expanded nodesC* = 40, cost 50, 3512 expanded nodesC* = 42, cost 46, 4831 expanded nodesC* = 28, cost 34, 194 expanded nodesC* = 37, cost 41, 5666 expanded nodesC* = 35, cost 35, 78 expanded nodesC* = 41, cost 47, 175 expanded nodesC* = 28, cost 40, 13413 expanded nodesC* = 28, cost 32, 2187 expanded nodesC* = 26, cost 42, 971 expanded nodesC* = 34, cost 38, 1074 expanded nodesC* = 24, cost 32, 218 expanded nodesC* = 39, cost 41, 914 expanded nodesC* = 31, cost 31, 793 expanded nodesC* = 27, cost 29, 702 expanded nodesC* = 38, cost 50, 33926 expanded nodesC* = 38, cost 44, 10755 expanded nodesC* = 38, cost 38, 2172 expanded nodesC* = 51, cost 59, 5786 expanded nodesC* = 25, cost 33, 165 expanded nodesC* = 32, cost 38, 3430 expanded nodesC* = 37, cost 41, 3805 expanded nodesC* = 39, cost 41, 107103 expanded nodesC* = 35, cost 37, 716 expanded nodesC* = 40, cost 52, 2847 expanded nodesC* = 47, cost 51, 6071 expanded nodesC* = 43, cost 49, 4381 expanded nodesC* = 40, cost 40, 1220 expanded nodesC* = 42, cost 50, 24375 expanded nodesC* = 37, cost 41, 11017 expanded nodesC* = 38, cost 42, 10758 expanded nodesC* = 35, cost 47, 4603 expanded nodesC* = 39, cost 53, 1141 expanded nodesC* = 30, cost 34, 540 expanded nodesC* = 33, cost 39, 5453 expanded nodesC* = 27, cost 29, 1131 expanded nodesC* = 47, cost 59, 41226 expanded nodesC* = 40, cost 42, 26929 expanded nodesC* = 36, cost 36, 2680 expanded nodesC* = 33, cost 37, 664 expanded nodesC* = 36, cost 42, 21777 expanded nodesC* = 40, cost 44, 68006 expanded nodesC* = 37, cost 39, 33005 expanded nodesC* = 33, cost 43, 2282 expanded nodesC* = 32, cost 34, 895 expanded nodesC* = 40, cost 48, 1794 expanded nodesC* = 43, cost 47, 52797 expanded nodesC* = 35, cost 39, 3243 expanded nodesC* = 41, cost 47, 11391 expanded nodesC* = 45, cost 49, 11843 expanded nodesC* = 38, cost 46, 616 expanded nodesC* = 42, cost 54, 83692 expanded nodesC* = 30, cost 34, 4773 expanded nodesC* = 34, cost 38, 3544 expanded nodesC* = 38, cost 40, 5637 expanded nodesC* = 21, cost 23, 781 expanded nodesmedian
Frontier: the cost of each w (all 200 instances)
1.01.52.02.5100010⁴median expanded nodes (log scale)cost / C*w=1.00w=1.50w=2.00w=3.00w=5.00
  • one instance (top) / mean cost (bottom)
  • worst cost among 200
  • bound w C∗w\,C^*
  • median nodes
2.00
Median expanded nodes4524
Median reduction versus A*5.9×
Mean cost / C∗C^*1.156
Worst cost / C∗C^*1.615
Guaranteed bound ww2.00
Instances solved optimally11.0 %
None of 200 instances exceeds the bound; the worst case is 1.62, below w=2.00w = 2.00, and the mean is 1.16: the bound is a guarantee, not a prediction.
200 instances of the 15-puzzle solved with weighted A∗ and Manhattan, without reopening, for 11 values of ww. Top: each point is an instance, with nodes expanded (logarithmic scale) versus cost divided by optimum, the bound line ww and median nodes. Bottom: the frontier, median nodes versus mean cost (solid line) and worst cost (dashed) for all ww; click a point to select it. Instances are random walks of 40 to 70 moves from the goal (mean C∗C^* 35.8), easier than Korf's so A∗ with w=1w = 1 fits in memory; data are generated by gen_wastar.py in this lesson's interactive folder.

Two lessons emerge from the figure. First, the bound is almost never reached. With w=2w = 2 mean cost is 1.156 times optimal and the worst of 200 cases 1.615; with w=5w = 5, mean 1.694 and worst case 2.5, half what the bound allows. The bound is what you can guarantee someone; what you observe is much better. Second, the first increases of ww save the most. Going from w=1w = 1 to w=1.5w = 1.5 divides median expanded nodes by 4.3 (26 870 to 6220) for 4.7% more mean cost; going from 2 to 5 divides it by only 2.4 (4524 to 1862) and worsens mean cost by over 50 points. The frontier quickly flattens: beyond w≈2w \approx 2 you pay much quality for little time.

Beware a counterintuitive consequence: increasing ww does not always reduce nodes on a particular instance. On the first instance in the set, w=2w = 2 expands 2797 nodes and w=2.5w = 2.5, 16 517: search rushes down a branch overvalued by the heuristic and must escape it. The median is monotone; individual instances need not be.

Anytime search with ARA*

Often you do not know how much time you have: a robot must move now, but given another half second it can improve its plan. An anytime algorithm gives a solution quickly and improves it for as long as allowed.

The naive approach runs weighted A* with w=3w = 3, then w=2.5w = 2.5, and so on to 1, starting from scratch each time. ARA* (anytime repairing A*, Likhachev, Gordon and Thrun, 2003) reuses work between searches. The idea is local inconsistency: a state whose gg has decreased since it was last expanded has not yet propagated that improvement to successors.

  1. Each search (ImprovePath) is WA* without reopening with f(s)=g(s)+w h(s)f(s) = g(s) + w\,h(s). If the gg of an already closed state decreases, it is not reopened: it is recorded in an INCONS list.
  2. When a search ends, lower ww, move INCONS states to OPEN, reorder OPEN with the new ww, empty CLOSED and search again. The entire already calculated gg tree is preserved: only inconsistent nodes are re-expanded.
  3. ImprovePath stops when f(meta)≤min⁡s∈OPENf(s)f(\text{meta}) \le \min_{s \in \text{OPEN}} f(s), not when it removes the goal (the goal may not re-enter OPEN).

Besides bound ww, ARA* calculates a tighter a posteriori bound,

ε′=min⁡(w, g(meta)min⁡s∈OPEN∪INCONS(g(s)+h(s))),\eps' = \min\Big(w,\ \frac{g(\text{meta})}{\min_{s \in \text{OPEN} \cup \text{INCONS}} \big(g(s) + h(s)\big)}\Big),

because the numerator is the cost of the solution at hand and the denominator, the smallest unweighted ff of a locally inconsistent state, is according to the authors a lower bound on optimal cost. Their paper evaluates it on simulated robotic arms: with 6 degrees of freedom, the authors report up to a 6-fold speedup for ARA* over successive searches from scratch; on the same arm with nonuniform costs, it reaches bound 4.5 after about 59 000 expansions, versus 12.5 million for repeated weighted A*. In a simpler setting, lowering ww from 3 to 1 in steps of 0.02 until certifying optimality cost only 4% more than a single optimal A*. Anytime planners of this family are common in robots with real-time constraints, as you will see in motion planning.

Lab: weighted A* and ARA* on grid maps

The maps are caves generated by a cellular automaton, as in many dungeon video games: the map is randomly filled with 45% walls and smoothed five times (a cell is a wall if 5 or more cells in its 3×33\times 3 block are walls). Movement is in 8 directions, with cost 1 horizontally and vertically and 2\sqrt 2 diagonally, without cutting corners; the heuristic is octile distance, consistent for that movement model.

[ ]Lab 2: cave maps and weighted A*Browser
import numpy as np, heapq, math, time

def cueva(n, semilla, relleno=0.45, pasos=5):
    """Mapa de cuevas por autómata celular: True = muro. Se queda con la componente libre más grande."""
    rng = np.random.default_rng(semilla)
    m = rng.random((n, n)) < relleno
    m[0, :] = m[-1, :] = m[:, 0] = m[:, -1] = True
    for _ in range(pasos):
        p = np.pad(m, 1, constant_values=True)
        vecinos = sum(p[1 + dy:n + 1 + dy, 1 + dx:n + 1 + dx] for dy in (-1, 0, 1) for dx in (-1, 0, 1))
        m = vecinos >= 5                         # muro si hay 5 o más muros en su bloque 3x3
        m[0, :] = m[-1, :] = m[:, 0] = m[:, -1] = True
    libres = list(zip(*np.nonzero(~m)))
    comp, mejor = {}, []
    for c in libres:                             # componentes 4-conexas por inundación
        if c in comp:
            continue
        pila, actual = [c], []
        comp[c] = len(mejor)
        while pila:
            y, x = pila.pop()
            actual.append((y, x))
            for v in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                if not m[v] and v not in comp:
                    comp[v] = 0
                    pila.append(v)
        if len(actual) > len(mejor):
            mejor = actual
    m[:] = True
    for c in mejor:
        m[c] = False
    return m

R2 = math.sqrt(2)
MOV = [(1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0), (1, 1, R2), (1, -1, R2), (-1, 1, R2), (-1, -1, R2)]

def vecinos(m, c):
    y, x = c
    out = []
    for dy, dx, k in MOV:
        if m[y + dy, x + dx]:
            continue
        if dy and dx and (m[y + dy, x] or m[y, x + dx]):
            continue                             # sin cortar esquinas en diagonal
        out.append(((y + dy, x + dx), k))
    return out

def octil(a, b):
    dy, dx = abs(a[0] - b[0]), abs(a[1] - b[1])
    return dx + dy + (R2 - 2) * min(dx, dy)      # consistente con movimientos de coste 1 y raíz de 2

def wastar(m, s, t, w):
    """A* ponderado sin reapertura: f = g + w h. Devuelve (coste, expansiones)."""
    g = {s: 0.0}
    abiertos = [(w * octil(s, t), 0.0, s)]
    cerrados = set()
    while abiertos:
        _, gs, c = heapq.heappop(abiertos)
        if c in cerrados or gs > g[c]:
            continue
        if c == t:
            return gs, len(cerrados)
        cerrados.add(c)
        for v, k in vecinos(m, c):
            if v not in cerrados and gs + k < g.get(v, math.inf):
                g[v] = gs + k
                heapq.heappush(abiertos, (g[v] + w * octil(v, t), g[v], v))
    return math.inf, len(cerrados)

mapa = cueva(120, 1)
libres = np.argwhere(~mapa)
d = libres[:, 1] - libres[:, 0]
inicio = tuple(int(v) for v in libres[np.argmax(d)])      # la casilla libre más cercana a la esquina superior derecha
meta = tuple(int(v) for v in libres[np.argmin(d)])        # y a la inferior izquierda
print(f"mapa {mapa.shape}, {len(libres)} casillas libres, de {inicio} a {meta}")
c_opt, n_opt = wastar(mapa, inicio, meta, 1.0)
print(f"A* (w = 1): coste óptimo {c_opt:.2f}, {n_opt} expansiones")
for w in (1.25, 1.5, 2.0, 3.0, 5.0):
    c, n = wastar(mapa, inicio, meta, w)
    print(f"w = {w:4}: coste {c:8.2f} = {c / c_opt:.3f}·C*   {n:6d} expansiones ({n / n_opt:.2f} de las de A*)")

On this map of 9302 free cells, A* expands 6216 to find the optimal path, cost 192.41. With w=1.5w = 1.5, 30% of those expansions suffice and the path is 2.3% longer; with w=3w = 3, 16% of expansions and 8% longer. Again, the bounds (50% and 200% longer) are far away.

Now ARA*, with weight sequence 3,2.5,2,1.5,1.25,1.1,13, 2.5, 2, 1.5, 1.25, 1.1, 1, compared against repeating weighted A* from scratch at each weight.

[ ]ARA*: reusing search as w decreasesBrowser
def ara(m, s, t, pesos):
    """ARA* (Likhachev, Gordon y Thrun, 2003). Devuelve por iteración (w, coste, cota eps', expansiones acumuladas)."""
    g = {s: 0.0, t: math.inf}
    h = lambda c: octil(c, t)
    abiertos = {s}                               # OPEN (como conjunto; el montículo admite entradas obsoletas)
    incons = set()
    expansiones = 0
    salida = []
    for w in pesos:
        abiertos |= incons                       # INCONS vuelve a OPEN
        incons = set()
        cola = [(g[c] + w * h(c), g[c], c) for c in abiertos]
        heapq.heapify(cola)
        cerrados = set()
        # ImprovePath: mientras f(meta) = g(meta) supere el menor f de OPEN
        while cola and g[t] > cola[0][0] - 1e-12:
            _, gc, c = heapq.heappop(cola)
            if c not in abiertos or gc > g[c]:
                continue                         # entrada obsoleta
            abiertos.discard(c)
            cerrados.add(c)
            expansiones += 1
            for v, k in vecinos(m, c):
                if g[c] + k < g.get(v, math.inf):
                    g[v] = g[c] + k
                    if v not in cerrados:
                        abiertos.add(v)
                        heapq.heappush(cola, (g[v] + w * h(v), g[v], v))
                    else:
                        incons.add(v)            # localmente inconsistente y ya expandido en esta iteración
        cota_inf = min((g[c] + h(c) for c in abiertos | incons), default=math.inf)
        eps = min(w, g[t] / cota_inf) if cota_inf > 0 else w
        salida.append((w, g[t], eps, expansiones))
    return salida

pesos = [3.0, 2.5, 2.0, 1.5, 1.25, 1.1, 1.0]
res_ara = ara(mapa, inicio, meta, pesos)
print("   w     coste   coste/C*   cota eps'   expansiones acumuladas")
for w, c, e, n in res_ara:
    print(f"{w:5.2f} {c:9.2f} {c / c_opt:9.3f} {e:10.3f} {n:12d}")
reinicios, acum = [], 0
for w in pesos:
    c, n = wastar(mapa, inicio, meta, w)
    acum += n
    reinicios.append((w, c, acum))
print(f"\nrepetir A* ponderado desde cero para cada w: {acum} expansiones; ARA*: {res_ara[-1][3]} "
      f"({acum / res_ara[-1][3]:.1f} veces menos)")
[ ]The anytime curveBrowser
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6.4, 3.6))
xa = [n for *_, n in res_ara]
ax.step(xa, [c / c_opt for _, c, _, _ in res_ara], where="post", marker="o", label="ARA*: coste / C*")
ax.step(xa, [e for _, _, e, _ in res_ara], where="post", linestyle="--", label="ARA*: cota ε'")
ax.step([n for *_, n in reinicios], [c / c_opt for _, c, _ in reinicios], where="post", marker="s",
        label="A* ponderado desde cero")
ax.axhline(1, color="gray", lw=0.8)
ax.set_xscale("log")
ax.set_xlabel("expansiones acumuladas")
ax.set_ylabel("coste / C*")
ax.legend()
plt.tight_layout()
plt.show()

Read the table from top to bottom: each row is a later moment. After 969 expansions ARA* already has a path costing 207.76 (8% above optimal) and knows it is at most 32.6% worse (ε′=1.326\eps' = 1.326, much better than bound w=3w = 3). Searches with w=2.5w = 2.5 and w=2w = 2 expand nothing: the stopping condition already holds with the same OPEN. With w=1.25w = 1.25 the path improves to 1% and with w=1w = 1 reaches optimal, with ε′=1\eps' = 1 as certificate. In total ARA* makes 14 473 expansions versus 19 617 for seven searches from scratch: 1.4 times fewer, far from the robotic arm’s factor 6, because here each search from scratch is cheap compared with the last. Notice the price of anytime: a single A* with w=1w = 1 costs 6216 expansions, less than half the full sequence, whereas on Likhachev, Gordon and Thrun’s arm the overhead was 4%. The table shows why: the last two searches, with w=1.1w = 1.1 and w=1w = 1, expand 9209−4571=46389209 - 4571 = 4638 and 14 473−9209=526414\,473 - 9209 = 5264 states, each nearly as many as a complete A*. With ww near 1, search no longer rushes toward the goal and must revisit almost the entire region A* explores; on this map that region is small and the quick initial searches save none of it. ARA* pays off when a quick first answer is worth more than a late optimal one; if only the optimum matters, direct A* is cheaper.

Abstractions and pattern databases

The third response changes the problem: if the heuristic were almost perfect, A* or IDA* would go almost straight to the goal. The previous lesson’s relaxed-problem heuristics were computed on the fly. An abstraction enables much stronger heuristics in exchange for precomputing and storing them.

Condition 1 says every path of SS projects to a path in S′S' that is no more expensive. This suffices for everything we need, as you will prove in a guided exercise: hϕh_\phi is admissible and consistent. The previous lesson’s relaxation is the case of identity ϕ=\phi = with more or cheaper edges; abstraction also merges states.

In the 15-puzzle, the abstraction of a pattern TT (a set of tiles) erases the identity of the others: an abstract state is the position of TT tiles and the blank, and the other tiles are indistinguishable. Moving any tile remains a cost-1 edge (or 0 if endpoints coincide, which does not happen because the blank moves). The abstract space of a pattern of kk tiles has 16!/(15−k)!16!/(15 - k)! states rather than 16!/216!/2, and for k=5k = 5 there are 5 765 7605\,765\,760: it can be traversed completely.

One backward search solves all subproblems at once, and its cost is amortized over all instances sharing the goal. What remains is the index: a function mapping each abstract state to a gapless array slot.

Indexing the table: ranking partial permutations

An abstract state of a pattern of kk tiles is a tuple (p1,…,pk)(p_1, \dots, p_k) of distinct cells from {0,…,n−1}\{0, \dots, n - 1\} (with n=16n = 16): an kk-permutation of nn elements, and there are P(n,k)=n!/(n−k)!P(n, k) = n!/(n - k)! (permutations without repetition). The optimal table has exactly P(n,k)P(n, k) entries, and we need a quickly computed bijection between kk-permutations and {0,…,P(n,k)−1}\{0, \dots, P(n, k) - 1\}. The natural one is lexicographic position:

rank⁡(p1,…,pk)=∑i=1k(pi−#{j<i:pj<pi})⋅P(n−i, k−i).\operatorname{rank}(p_1, \dots, p_k) = \sum_{i=1}^{k} \big(p_i - \#\{j < i : p_j < p_i\}\big)\cdot P(n - i,\ k - i).

Factor pi−#{j<i:pj<pi}p_i - \#\{j < i : p_j < p_i\} counts how many still-free cells are smaller than pip_i: how many lexicographically earlier choices existed at position ii, each leaving P(n−i,k−i)P(n - i, k - i) ways to complete the rest. For n=16n = 16 and k=5k = 5, the multipliers are P(15,4)=32 760P(15, 4) = 32\,760, P(14,3)=2184P(14, 3) = 2184, P(13,2)=156P(13, 2) = 156, P(12,1)=12P(12, 1) = 12 and 11. The inverse, unrank, reverses the count with successive integer divisions; you will implement it in a coding exercise.

This is minimal perfect hashing: each key goes to a different slot and none is left over. A faster alternative to compute is the sparse index ∑ipi 16i−1\sum_i p_i\,16^{i-1}, which uses only bit shifts but wastes combinations with repeated cells: 165=1 048 57616^5 = 1\,048\,576 entries for 524 160524\,160 states, twice as many. Felner, Korf and Hanan used sparse indexing for the 5-5-5 partition (3 145 728 bytes, “3 megabytes”) and compact indexing for 7-8, where sparse would not fit in memory. What is never advisable is a general-purpose dictionary or hash table (with chaining or open addressing): storing the key alongside the value multiplies memory, as the lab shows.

Additive pattern databases

With multiple PDBs you can combine values. The maximum is always admissible because each is. The sum would be much stronger, but is generally not admissible: if both tables count blank moves or tiles that are not theirs, the same real move is counted twice. Culberson and Schaeffer combined their two 15-puzzle tables by maximum for that reason.

Proof

Define ci(u,v)=1c_i(u, v) = 1 if move (u,v)(u, v) moves a tile in TiT_i and 0 otherwise. Each real move moves exactly one tile, and that tile belongs to exactly one group (tiles outside all groups are treated as one-tile groups whose PDB is their Manhattan distance), so ∑ici(u,v)=1=c(u,v)\sum_i c_i(u, v) = 1 = c(u, v). Abstraction ϕi\phi_i with costs cic_i satisfies condition 1 of the abstraction definition, so hi(s)=di(ϕi(s))h_i(s) = d_i(\phi_i(s)) is admissible and consistent with respect to cic_i: hi(u)≤ci(u,v)+hi(v)h_i(u) \le c_i(u, v) + h_i(v) and hi(s)≤ci(π)h_i(s) \le c_i(\pi) for every path π\pi from ss to the goal. Summing over ii, h(u)≤∑ici(u,v)+h(v)=c(u,v)+h(v)h(u) \le \sum_i c_i(u, v) + h(v) = c(u, v) + h(v), and for optimal path π∗\pi^*, h(s)≤∑ici(π∗)=c(π∗)=C∗h(s) \le \sum_i c_i(\pi^*) = c(\pi^*) = C^*.

∎

The proof uses disjointness at a single point, ∑ici=c\sum_i c_i = c: if two groups shared a tile, its moves would be counted twice; if the tables counted blank moves, all groups would simultaneously count every move shifting the blank without moving their tiles. Manhattan distance is the extreme case: fifteen one-tile groups whose tables are each tile’s distance to its cell.

To save memory, the table does not store the blank’s position: it stores the minimum over all its positions. Felner, Korf and Hanan did this, and the value remains admissible because it is no greater than the value with the blank in its place.

InteractivePattern database builder
blank
patternkentriesBFS statestimemean h
1 2 3 5 65524 k5.77 M……
4 8 9 12 135524 k5.77 M……
7 10 11 14 155524 k5.77 M……
entries = 16!/(16 − k)!; BFS states = 16!/(15 − k)! (pattern tiles and blank); mean h over all entries
heuristicmean h(s₀)IDA* nodesoptimal
Manhattan………
first PDB + Manhattan for remainder………
sum of PDBs………
five fixed instances with C* = 31, 34, 39, 40, 43 (mean C* 37.4); nodes = total generated over all five
  • pattern 1
  • pattern 2
  • pattern 3
  • no pattern
Total entries (1 byte each)1.57 M = 1.50 MiB
Click a tile on the goal board to move it to pattern 1, 2, 3 or none. For each pattern, the table gives entries 16!/(16−k)!16!/(16 - k)! and the states visited by backward search, 16!/(15−k)!16!/(15 - k)! (tiles and blank); your browser really builds tables of up to 5 tiles in the background and measures time and mean hh. Below, IDA∗ solves five fixed instances (C∗=31C^* = 31 to 4343) with Manhattan, the first PDB and the sum, counting generated nodes. Tiles without a pattern contribute their Manhattan distance to the sum. Turn off the switch: the tables also count blank moves. What happens to the sum and solutions?

With the 5-5-5 partition, the sum of PDBs reduces IDA* nodes generated across five instances from 3 042 553 with Manhattan to 160 104: about 19 times fewer, using 1.5 MB of tables. With one 5-tile PDB and Manhattan for the rest, the reduction is much smaller: 1 520 661 nodes, only half of Manhattan. A table captures interactions among its five tiles; Manhattan still governs the rest of the board. Turning off the switch makes the sum of three tables exceed C∗C^* on all five instances and IDA* returns longer-than-optimal solutions: an overestimating heuristic silently breaks optimality. With those tables the only valid combination is maximum.

Lab: IDA* with an additive 5-5-5 PDB

We build the figure’s three tables, 524 160 entries each, by backward 0-1 breadth-first search on NumPy arrays. The abstract state (five tiles and the blank) is encoded in an integer with 4 bits per position, so reading the cell of tile ii is (s >> 4*i) & 15. Each search level has two phases: first the cost-0 closure, in which the blank slides through free cells without changing distance, and then cost-1 moves, in which a pattern tile adjacent to the blank slides into it. Everything operates on the entire frontier at once, without Python loops per state.

[ ]Lab 1: the first pattern databaseBrowser
import numpy as np

def pdb_dispersa(patron):
    """Búsqueda hacia atrás 0-1 en el espacio abstracto (fichas del patrón + hueco).

    Índice disperso del estado: hueco·16^k + sum(p_i·16^i), con p_i la casilla de la i-ésima ficha del patrón.
    Mover el hueco a una casilla libre cuesta 0; mover una ficha del patrón cuesta 1. Devuelve, para cada
    colocación de las fichas, el mínimo sobre las posiciones del hueco (127 si la colocación es imposible).
    """
    k = len(patron)
    SH = 4 * k
    dist = np.full(16 << SH, -1, dtype=np.int8)
    inicio = sum(t << (4 * i) for i, t in enumerate(patron))   # meta abstracta: hueco en la casilla 0
    dist[inicio] = 0
    frontera = np.array([inicio], dtype=np.int64)
    nivel = 0
    while frontera.size:
        capa, cur = [frontera], frontera
        while cur.size:                          # cierre a coste 0: el hueco recorre las casillas libres
            b = cur >> SH
            ocupada = np.zeros((cur.size, 16), bool)
            filas = np.arange(cur.size)
            for i in range(k):
                ocupada[filas, (cur >> (4 * i)) & 15] = True
            nuevos = []
            for d, ok in ((-4, b >= 4), (4, b < 12), (-1, (b & 3) > 0), (1, (b & 3) < 3)):
                m = ok.copy()
                m[m] = ~ocupada[filas[m], b[m] + d]
                n = cur[m] + (d << SH)
                n = n[dist[n] < 0]
                dist[n] = nivel
                nuevos.append(n)
            cur = np.concatenate(nuevos)
            capa.append(cur)
        todos = np.concatenate(capa)
        b = todos >> SH
        sig = []
        for i in range(k):                       # coste 1: la ficha i, vecina del hueco, se desliza a él
            p = (todos >> (4 * i)) & 15
            for d in (-4, 4, -1, 1):
                m = p == b + d
                if d == -1:
                    m &= (b & 3) > 0
                if d == 1:
                    m &= (b & 3) < 3
                n = todos[m] + (d << SH) - (d << (4 * i))
                sig.append(n[dist[n] < 0])
        frontera = np.unique(np.concatenate(sig))
        dist[frontera] = nivel + 1
        nivel += 1
    d2 = dist.reshape(16, -1)                    # fila = posición del hueco
    return np.where(d2 < 0, 127, d2).min(axis=0).astype(np.int8)

# multiplicadores del rango lexicográfico de una 5-permutación de {0..15}: P(15,4), P(14,3), P(13,2), P(12,1), 1
MULT = np.array([32760, 2184, 156, 12, 1])

def compactar(dispersa, k=5):
    """De la tabla dispersa (16^k entradas) a la compacta (16!/(16-k)! entradas) indexada por el rango."""
    idx = np.arange(dispersa.size)
    P = np.stack([(idx >> (4 * i)) & 15 for i in range(k)], axis=1)
    validas = dispersa < 127
    P = P[validas]
    r = np.zeros(len(P), dtype=np.int64)
    for i in range(k):
        menores = (P[:, :i] < P[:, i:i + 1]).sum(axis=1)   # casillas ya usadas por fichas anteriores
        r += (P[:, i] - menores) * MULT[i]
    tabla = np.full(len(P), -1, dtype=np.int8)
    tabla[r] = dispersa[validas]
    assert (tabla >= 0).all()                    # el rango cubre exactamente [0, 524160)
    return tabla

GRUPOS = [(1, 2, 3, 5, 6), (4, 8, 12, 9, 13), (7, 10, 11, 14, 15)]
t = time.perf_counter()
disp = [pdb_dispersa(GRUPOS[0])]
pdb = [compactar(disp[0])]
print(f"patrón {GRUPOS[0]}: {pdb[0].size:,d} entradas en {time.perf_counter() - t:.2f} s")
print(f"  h media {pdb[0].mean():.3f}, máxima {pdb[0].max()}, histograma:", np.bincount(pdb[0]))
[ ]The second tableBrowser
t = time.perf_counter()
disp.append(pdb_dispersa(GRUPOS[1]))
pdb.append(compactar(disp[-1]))
print(f"patrón {GRUPOS[1]} en {time.perf_counter() - t:.2f} s")
[ ]The third table and memoryBrowser
t = time.perf_counter()
disp.append(pdb_dispersa(GRUPOS[2]))
pdb.append(compactar(disp[-1]))
print(f"patrón {GRUPOS[2]} en {time.perf_counter() - t:.2f} s")
for g, tab in zip(GRUPOS, pdb):
    md_media = sum(np.mean([MD[p][t] for p in range(16)]) for t in g)   # cada ficha, uniforme en las 16 casillas
    print(f"  {g}: media {tab.mean():.3f} (Manhattan de esas fichas: {md_media:.3f}), máxima {tab.max()}")
print(f"compactas: {sum(t.nbytes for t in pdb):,d} bytes   dispersas (16^5 por tabla): {sum(d.size for d in disp):,d} bytes")

Each table has P(16,5)=524 160P(16, 5) = 524\,160 entries and the compactar assertion confirms the rank covers all without collisions. The first has mean 13.149 versus 12.000 for the Manhattan distance of the same five tiles: the PDB adds the cost of their interactions (linear conflicts, tiles obstructing one another). The three compact tables occupy 1 572 480 bytes; sparse tables twice that. What about a dictionary?

[ ]Dictionary versus arrayBrowser
import itertools
tracemalloc.start()
como_dict = {perm: int(v) for perm, v in zip(itertools.permutations(range(16), 5), pdb[0])}
pico_dict = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
print(f"dict de tuplas: {len(como_dict):,d} entradas, {pico_dict / 1e6:.1f} MB")
print(f"array compacto: {pdb[0].nbytes / 1e6:.2f} MB  ->  el dict ocupa {pico_dict / pdb[0].nbytes:.0f} veces más")
del como_dict

itertools.permutations generates 5-permutations in exact lexicographic order, so array entry rr and the rr-th dictionary key are the same state. The dictionary occupies 68 times more: each entry stores a tuple of five integers and its hash, versus one byte in the array. With the 7-8 partition the difference separates what fits in memory from what does not.

Finally, IDA* with the sum of the three tables. Each move moves one tile, so only its group’s table changes: the code updates that group’s cells, recalculates its rank and looks up one entry.

[ ]IDA* with the additive 5-5-5 PDBBrowser
GRUPO_DE, PUESTO = [0] * 16, [0] * 16
for gi, g in enumerate(GRUPOS):
    for s, t in enumerate(g):
        GRUPO_DE[t], PUESTO[t] = gi, s
MULT_L = [int(m) for m in MULT]

def rango(ps):
    """Rango lexicográfico de la 5-permutación ps (casillas de las fichas del patrón, en su orden)."""
    r = 0
    for i, p in enumerate(ps):
        r += (p - sum(q < p for q in ps[:i])) * MULT_L[i]
    return r

def ida_15(tablero, usar_pdb=True, max_nodos=10**7):
    """IDA* para el 15-puzzle con la PDB aditiva o con Manhattan. Devuelve (C*, nodos generados)."""
    s = list(tablero)
    pos = {t: p for p, t in enumerate(s)}
    casillas = [[pos[t] for t in g] for g in GRUPOS]          # casillas de las fichas de cada patrón
    hp = [int(pdb[i][rango(casillas[i])]) for i in range(3)]
    md = manhattan(s)
    nodos = 0
    def dfs(b, g, umbral, prev):
        nonlocal nodos, md
        h = hp[0] + hp[1] + hp[2] if usar_pdb else md
        if g + h > umbral:
            return g + h
        if md == 0:
            return -1
        minimo = 1 << 30
        for q in NBRS[b]:
            if q == prev:
                continue
            nodos += 1
            if nodos > max_nodos:
                raise RuntimeError("demasiados nodos")
            t = s[q]
            gi, k = GRUPO_DE[t], PUESTO[t]
            dm = MD[b][t] - MD[q][t]
            s[b], s[q] = t, 0
            md += dm
            viejo = hp[gi]
            casillas[gi][k] = b
            hp[gi] = int(pdb[gi][rango(casillas[gi])])
            r = dfs(q, g + 1, umbral, b)
            s[q], s[b] = t, 0
            md -= dm
            casillas[gi][k] = q
            hp[gi] = viejo
            if r == -1:
                return -1
            minimo = min(minimo, r)
        return minimo
    umbral = hp[0] + hp[1] + hp[2] if usar_pdb else md
    while True:
        r = dfs(s.index(0), 0, umbral, -1)
        if r == -1:
            return umbral, nodos
        umbral = r

INSTANCIAS = [
    (5, 1, 2, 3, 9, 11, 6, 7, 13, 4, 12, 15, 0, 8, 14, 10),
    (6, 5, 3, 7, 10, 0, 8, 11, 13, 4, 2, 9, 12, 14, 1, 15),
    (7, 0, 5, 2, 1, 6, 12, 8, 4, 13, 15, 3, 14, 9, 10, 11),
    (5, 3, 11, 14, 7, 2, 4, 0, 8, 1, 15, 6, 12, 10, 13, 9),
    (1, 0, 5, 11, 4, 3, 10, 2, 15, 9, 6, 14, 12, 7, 13, 8),
]
res_pdb = []
for tab in INSTANCIAS:
    c, n = ida_15(tab)
    res_pdb.append((c, n))
    h_pdb = sum(int(pdb[i][rango([tab.index(x) for x in g])]) for i, g in enumerate(GRUPOS))
    print(f"C* = {c}   h0: Manhattan {manhattan(tab)}, PDB {h_pdb}   IDA*+PDB: {n:8,d} nodos")
[ ]The same search with ManhattanBrowser
t_md = t_pdb = 0.0
n_md = n_pd = 0
for tab, (c_pdb, n_pdb) in zip(INSTANCIAS[:3], res_pdb):
    t = time.perf_counter()
    c, n = ida_15(tab, usar_pdb=False)
    t_md += time.perf_counter() - t
    t = time.perf_counter()
    ida_15(tab)                                  # la misma búsqueda con la PDB, cronometrada aparte
    t_pdb += time.perf_counter() - t
    n_md, n_pd = n_md + n, n_pd + n_pdb
    assert c == c_pdb
    print(f"C* = {c}   IDA*+Manhattan: {n:9,d} nodos   frente a {n_pdb:7,d} con la PDB  ({n / n_pdb:5.1f} veces más)")
print(f"tiempo de las tres: Manhattan {t_md:.2f} s, PDB {t_pdb:.3f} s  ({t_md / t_pdb:.0f} veces menos con la PDB)")
print(f"nodos por segundo: Manhattan {n_md / t_md:,.0f}, PDB {n_pd / t_pdb:,.0f}")

These are the figure’s five instances, and node counts exactly match the interactive (which uses sparse indexing in JavaScript): two different implementations of the same search. The PDB raises h(s0)h(s_0) by 2 to 6 moves relative to Manhattan in four of five instances, and since nodes grow exponentially with C∗−hC^* - h, this translates to factors of 10 to 80 in the three compared by the cell. In the fourth, the PDB does not increase h(s0)h(s_0) (30 in both cases), but does increase interior tree values, and nodes still fall from 283 623 to 65 816 according to the interactive’s table.

Here time falls in the same proportion as nodes (about 50 times in the three instances), and nodes per second are almost equal for both heuristics. This is no accident: ida_15 updates both Manhattan distance and the PDB entry at every move, whichever it uses, so per-node cost is the same. An implementation that only added integers for Manhattan would be faster per node, as in the paper, where 5-5-5 generates 5.7 million nodes per second versus Manhattan’s 7.5 million. Memory: tables take 1.5 MB and search stores the current path.

Published results: the 15-puzzle and Rubik’s cube

Felner, Korf and Hanan (2004, table 1) solved 1000 random 15-puzzle instances (mean optimal cost 52.552) with IDA* and different heuristics. In static partitions the heuristic is the maximum of the partition sum and the sum of the same partition reflected across the main diagonal, looked up in the same tables.

HeuristicMean h(s0)h(s_0)Generated nodes (mean)SecondsMemory
Manhattan36.940401 189 630530
Additive PDB 5-5-541.5603 090 4050.5403 145 kB
Additive PDB 6-6-342.924617 5550.16333 554 kB
Additive PDB 7-845.63036 7100.028576 575 kB

Every move of mean h(s0)h(s_0) is valuable: from Manhattan to 7-8 the heuristic rises 8.7 moves and nodes fall by a factor of 10 900. Time falls less, from 53 s to 28 ms (about 1900 times using the table’s rounded values; “over 2000,” according to the paper), because each node costs more: its nodes-per-second column gives 7.5 million with Manhattan, 5.7 million with 5-5-5 and 1.4 million with 7-8. Korf (1997) summarized this in a conjecture: IDA* time with a PDB is approximately n/mn/m, space size divided by table memory.

Rubik’s cube is the other classic example and shows the limits of additivity. Korf (1997) found the first optimal solutions of random cubes with IDA* and three PDBs: the 8 corners, with 8!⋅37=88 179 8408!\cdot 3^7 = 88\,179\,840 states (values 0 to 11 stored in 4 bits: 44 089 920 bytes, mean hh 8.764), and two groups of 6 edges, with 12!/6!⋅26=42 577 92012!/6!\cdot 2^6 = 42\,577\,920 states each (mean hh 7.668). They cannot be added: each turn moves four corners and four edges at once, so a real move is counted by the corner table and at least one edge table. Korf used the maximum, with mean hh 8.878 and 82 MB total. He solved 10 cubes generated with 100 random turns: one in 16 moves, three in 17 and six in 18 (median 18), generating between 3.7 billion and 1.02 trillion nodes at about 700 000 per second.

Heuristic bidirectional search: meeting in the middle

Bidirectional search without a heuristic naturally met in the middle: if each side advances by layers, neither goes beyond C∗/2C^*/2. With a heuristic the story was worse: classical bidirectional algorithms guided by hh guarantee nothing similar, and in a Barker and Korf experiment on Towers of Hanoi, BS* often expanded nodes at depth 13 in each direction with solutions costing at most 16. Holte, Felner, Sharon and Sturtevant (2016) presented MM, the first heuristic bidirectional algorithm guaranteed to meet in the middle.

MM maintains two searches, forward from ss with hFh_F (estimating distance to the goal) and backward from the goal with hBh_B (estimating distance to ss), always expanding the node of least priority

prF(n)=max⁡(fF(n), 2 gF(n)),prB(n)=max⁡(fB(n), 2 gB(n)).pr_F(n) = \max\big(f_F(n),\ 2\,g_F(n)\big), \qquad pr_B(n) = \max\big(f_B(n),\ 2\,g_B(n)\big).

Term 2g2g is key: a node more than C∗/2C^*/2 from its origin has pr>C∗pr > C^*, while optimal-path nodes near each end have pr≤C∗pr \le C^*, so they are expanded first. If UU is the cost of the best solution found (whenever one side generates a node open on the other), MM stops when

U≤max⁡(C, fmin⁡F, fmin⁡B, gmin⁡F+gmin⁡B+ε),U \le \max\big(C,\ f\min_F,\ f\min_B,\ g\min_F + g\min_B + \eps\big),

where CC is the minimum priority of the two OPEN sets and ε\eps the cheapest edge cost. The authors prove that with admissible hh, MM returns C∗C^*, never expands a node with f>C∗f > C^* and its forward (backward) search never expands a state more than C∗/2C^*/2 from the start (goal). MM0 is the h≡0h \equiv 0 case.

[ ]MM: bidirectional search meeting in the middleBrowser
def mm(m, s, t, h_activa=True, eps=1.0):
    """MM (Holte, Felner, Sharon y Sturtevant, 2016), con heurística octil hacia el extremo opuesto."""
    lados = []
    for origen, destino in ((s, t), (t, s)):
        h = (lambda c, d=destino: octil(c, d)) if h_activa else (lambda c: 0.0)
        lados.append({"g": {origen: 0.0}, "h": h, "abiertos": {origen}, "cerrados": set(),
                      "pr": [(max(h(origen), 0.0), 0.0, origen)], "f": [(h(origen), origen)], "gm": [(0.0, origen)],
                      "expandidos": []})
    U = math.inf
    def cima(L, nombre):
        cola = L[nombre]
        while cola and (cola[0][-1] not in L["abiertos"] or
                        (nombre == "pr" and cola[0][1] > L["g"][cola[0][-1]]) or
                        (nombre == "f" and cola[0][0] > L["g"][cola[0][-1]] + L["h"](cola[0][-1]) + 1e-9) or
                        (nombre == "gm" and cola[0][0] > L["g"][cola[0][-1]] + 1e-9)):
            heapq.heappop(cola)
        return cola[0][0] if cola else math.inf
    while lados[0]["abiertos"] and lados[1]["abiertos"]:
        prF, prB = cima(lados[0], "pr"), cima(lados[1], "pr")
        C = min(prF, prB)
        if U <= max(C, cima(lados[0], "f"), cima(lados[1], "f"), cima(lados[0], "gm") + cima(lados[1], "gm") + eps):
            return U, lados
        L, O = (lados[0], lados[1]) if prF <= prB else (lados[1], lados[0])
        _, gn, n = heapq.heappop(L["pr"])
        L["abiertos"].discard(n)
        L["cerrados"].add(n)
        L["expandidos"].append(n)
        for v, k in vecinos(m, n):
            gv = L["g"][n] + k
            if gv >= L["g"].get(v, math.inf):
                continue
            L["g"][v] = gv
            L["cerrados"].discard(v)
            L["abiertos"].add(v)
            hv = L["h"](v)
            heapq.heappush(L["pr"], (max(gv + hv, 2 * gv), gv, v))
            heapq.heappush(L["f"], (gv + hv, v))
            heapq.heappush(L["gm"], (gv, v))
            if v in O["abiertos"]:
                U = min(U, gv + O["g"][v])
    return U, lados

def dijkstra(m, s):
    d = {s: 0.0}
    cola = [(0.0, s)]
    while cola:
        dc, c = heapq.heappop(cola)
        if dc > d[c]:
            continue
        for v, k in vecinos(m, c):
            if dc + k < d.get(v, math.inf):
                d[v] = dc + k
                heapq.heappush(cola, (d[v], v))
    return d

dS, dT = dijkstra(mapa, inicio), dijkstra(mapa, meta)
for nombre, activa in (("MM ", True), ("MM0", False)):
    U, lados = mm(mapa, inicio, meta, activa)
    lejosF = sum(dS[c] > c_opt / 2 + 1e-9 for c in lados[0]["expandidos"])
    lejosB = sum(dT[c] > c_opt / 2 + 1e-9 for c in lados[1]["expandidos"])
    print(f"{nombre}: coste {U:.2f} (C* = {c_opt:.2f}), expande {len(lados[0]['expandidos'])} hacia delante "
          f"y {len(lados[1]['expandidos'])} hacia atrás; más allá de C*/2 de su origen: {lejosF} y {lejosB}")
print(f"A*:  {n_opt} expansiones; Dijkstra desde el inicio: {sum(d <= c_opt for d in dS.values())} casillas con d <= C*")

On the lab 2 cave map, the cell checks the guarantee with exact Dijkstra distances: neither MM nor MM0 expands any cell more than C∗/2C^*/2 from its origin. MM expands 5325 cells across both sides, fewer than A*‘s 6216; MM0 expands 7100. This is not a rule: the same authors show that the heuristic can make MM expand more than MM0 (up to 4 times more in one pancake-puzzle experiment) and that, depending on heuristic, A*, MM0 or MM can win. The most cited practical rule is Barker and Korf’s (2015) conjecture: unidirectional heuristic search expands fewer nodes than bidirectional if more than half of its expanded nodes have g≤C∗/2g \le C^*/2. Holte and coauthors analyze it with their state-space region framework and show it can fail because it ignores nodes backward search expands near the goal and far from the start; they provide sufficient conditions for it to hold. On this map MM wins; on another, with another heuristic, it may not.

Choosing for your resources

The three families address different resources and can be combined: IDA* with an additive PDB uses linear search memory plus large heuristic memory, and DeepCubeA solved Rubik’s cube by combining a learned heuristic with batched weighted A* (covered in the last lesson of this topic).

SituationChoiceWhy
Huge space, few transpositions (puzzles, Rubik), integer costsIDA*O(d)\bigO(d) memory, few iterations, no memory management
Same case, but free memory and many queries with the same goalIDA* + additive PDB (or maximum without a valid partition)memory is spent once and improves all searches
Graph with many transpositions (maps, grids)A* or variants with a state table; SMA* if memory is the limitIDA* would re-explore equivalent paths exponentially many times
Real costs, linear memory requiredIDA* with minimum jump δ\delta, or RBFSavoid O(N2)\bigO(N^2) iterations; with δ\delta, cost ≤C∗+δ\le C^* + \delta
Immediate answer and quality guarantee neededWeighted A* with ww between 1.2 and 2most savings come from the first increases in ww
Unknown time, interruptibleARA*increasingly better solutions with bound ε′\eps', reusing work
One isolated query between distant points, good heuristicA*; try MM if most of A*‘s expansions are far from the startMM does not go beyond C∗/2C^*/2 on each side

Common mistakes

Exercises

NumericA six-tile PDB
A pattern database for 6 tiles of the 15-puzzle stores one byte per possible placement of those 6 tiles in 16 cells (compact index, without storing the blank). How many megabytes does it occupy? (1 MB = 10610^6 bytes.)
NumericThe corner table
In Rubik’s cube, the orientation of the last corner is fixed by the other seven. How many bytes does the 8-corner PDB occupy if each entry uses 4 bits?
NumericIDA* iterations on the 15-puzzle
IDA with Manhattan distance solves a 15-puzzle instance with $h(s_0) = 36$ and $C^ = 54$. How many iterations does it perform?
NumericARA*’s a posteriori bound
ARA* finishes a search with w=2w = 2 and finds a path costing g(meta)=120g(\text{meta}) = 120. The smallest g(s)+h(s)g(s) + h(s) among states in OPEN and INCONS is 100. What suboptimality bound ε′\eps' can it report?
QuizWhy they cannot be added
You build three PDBs for the 15-puzzle’s 5-5-5 partition with breadth-first search where every move costs 1 (including moves that only shift the blank among tiles outside the pattern), and use their sum as a heuristic. What happens and how can it be fixed?
QuizWhat weighted A* guarantees
You use weighted A* with w=2w = 2 and a consistent heuristic, without reopening closed nodes. Which statement is correct?
QuizChoosing for available resources
A warehouse robot plans on a 10610^6-cell grid with 8 connections, costs 1 and 2\sqrt 2, and octile heuristic. It must start moving in 50 ms, but the plan can keep improving while moving. What is most suitable?
QuizIDA*, RBFS and SMA*
Which statement about memory-limited searches is correct?
ProofThe weighted A* bound
Prove: With finite branching, costs ≥ε>0\ge \eps > 0, hh admissible, w≥1w \ge 1 and reopening of closed nodes, weighted A returns a solution of cost $C \le w\,C^$.
0
Let P=(s0=n0,…,nk)P = (s_0 = n_0, \dots, n_k) be an optimal path and suppose WA* has just selected a goal GG for expansion, with fw(G)=g(G)f_w(G) = g(G).

Step 1 of 4. What fact about OPEN do you need?

ProofAbstraction heuristics are admissible and consistent
Prove: If ϕ:S→S′\phi: S \to S' is an abstraction (each edge (u,v)(u, v) of SS satisfies ϕ(u)=ϕ(v)\phi(u) = \phi(v) or is an edge of S′S' with c′(ϕ(u),ϕ(v))≤c(u,v)c'(\phi(u), \phi(v)) \le c(u, v), y ϕ(G)⊆G′\phi(G) \subseteq G'), then h(s)=d′(ϕ(s),G′)h(s) = d'(\phi(s), G') is admissible and consistent.
0
Write d′d' for shortest distance in S′S' and let d′(x,x)=0d'(x, x) = 0.

Step 1 of 4. How do you prove admissibility?

CodeRank and unrank partial permutations
Implement rank(perm, n) and unrank(r, n, k) for kk-permutations of {0,…,n−1}\{0, \dots, n-1\} in lexicographic order: rank takes a tuple of kk distinct elements and returns its position in [0,n!/(n−k)!)[0, n!/(n-k)!), and unrank is its inverse (returning a tuple). The order must match itertools.permutations(range(n), k). Do not use itertools within the functions.
from math import perm as P   # P(n, k) = n!/(n-k)!

def rank(perm, n):
  """Posición lexicográfica de la k-permutación perm de {0..n-1}."""
  k = len(perm)
  r = 0
  # tu código
  return r

def unrank(r, n, k):
  """k-permutación de {0..n-1} que ocupa la posición r en orden lexicográfico."""
  # tu código
  return tuple()
Shift+Enter to run

Summary

Key idea
When A* runs out of memory, three approaches can be combined: depth-first search with thresholds on ff (IDA*, RBFS), accepting a worse solution with a provable bound (weighted A*, ARA*), or spending memory before search on a heuristic precomputed by abstraction (pattern databases, additive when each move is counted by one table).
  • IDA* repeats depth-first searches with threshold f≤θf \le \theta; the next threshold is the smallest pruned ff. It is optimal with admissible hh and uses O(d)\bigO(d) memory. With integer costs it takes at most C∗−h(s0)+1C^* - h(s_0) + 1 iterations (half with Manhattan, by parity); with real costs it may take one per node, and a minimum jump δ\delta fixes this at the price of C≤C∗+δC \le C^* + \delta. It does not detect transpositions.
  • RBFS stores the backed-up value of each alternative and uses O(bd)\bigO(bd) memory; SMA* uses all available memory by discarding the worst leaf.
  • Weighted A*, f=g+w hf = g + w\,h, guarantees C≤w C∗C \le w\,C^*; in practice overhead is much smaller than the bound and the first ww increases give almost all the savings.
  • ARA* lowers ww while reusing search (OPEN and INCONS), publishing at each step an a posteriori bound ε′\eps' tighter than ww.
  • A homomorphic abstraction gives an admissible, consistent heuristic. A PDB precomputes it by backward search and indexes it by partial-permutation rank, in an array of n!/(n−k)!n!/(n-k)! bytes.
  • PDBs can be added if groups are disjoint and each table counts only its own tiles’ moves; if one move affects several (Rubik’s cube), only the maximum is admissible.
  • MM, with priority max⁡(f,2g)\max(f, 2g), is heuristic bidirectional search guaranteed not to pass C∗/2C^*/2 in either direction.