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 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.
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:
- Linear memory. IDA* and RBFS search depth-first with the same guarantee as A*, paying in time for what they save in memory.
- 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.
- 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 .
Each iteration is pure depth-first search: memory is the current path, states, or if siblings are stored for iteration. Choosing the smallest pruned as the next threshold gives optimality.
Proof
First, thresholds never exceed . Let be an optimal path. While , the goal at the end of has , so some node of is pruned in iteration : the first on with (all previous ones have and are expanded). Since is admissible, that node has , so .
Second, thresholds strictly increase and every iteration is finite: with threshold , no path with more than edges has , and finite branching gives only finitely many such paths. Between and there are only finitely many values reachable by paths of cost , so after finitely many iterations (or a goal with is found earlier, impossible because every goal has ).
Finally, in the iteration with all nodes on have and none is pruned, so depth-first search reaches a goal. The first it visits has , hence cost exactly .
∎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.
How many iterations
With integer costs and integer , all values are integers, so the thresholds are distinct integers between and :
In the figure’s tree there are exactly . In the 15-puzzle with Manhattan the count is better still: each move changes by 1 and the moved tile’s Manhattan distance by , so changes by 0 or 2 and preserves parity. Thresholds advance by two and there are at most iterations.
Total time is controlled too. If the number of nodes with grows geometrically with the threshold, by ratio per iteration, the final iteration dominates and all earlier ones together cost at most a fraction 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 with that .
Real costs: the worst case
The preceding argument breaks down with real costs. If almost no two nodes have the same , each iteration raises the threshold just to the next and adds one or very few new nodes. In the worst case, if A* expands nodes with distinct , IDA* performs iterations and the -th expands nodes: expansions in total, versus A*‘s . In the figure’s tree, real costs yield 16 distinct values and 16 iterations.
The next cell measures this on the 8-puzzle with two cost sets: all moves cost 1, or moving tile costs , a different number between 1 and 1.5 for each tile. The heuristic is , admissible because each tile must move at least its Manhattan distance and each move costs .
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, and : thresholds are , five iterations, exactly . 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 each iteration:
Proof
Let be the threshold of the iteration finding the goal. The visited goal has , hence . If , and we are done. Otherwise, iteration found no goal, which by the preceding proof’s argument implies (with the entire optimal path has and none of it is pruned) and that the smallest pruned is . Therefore .
∎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 , iterations fall from 45 to 16 and nodes from 150 541 to 31 480, while the solution remains optimal. This is typical: bound 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 : cost 36.408, within the 38.318 bound. More refined variants choose the next threshold from the distribution of pruned 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.
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 , 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 ties are rare, each change advances little and regenerations multiply.
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 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 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 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 be an optimal path. Lemma: while WA* has not terminated, some on is in OPEN with . If is in OPEN, suffices. Otherwise let be the largest index such that has been expanded with ; on expansion received (it cannot be smaller) and entered or returned to OPEN, because closed nodes are reopened. By maximality of , has not since been expanded with that , so remains in OPEN.
When WA* selects a goal to expand, it has the smallest in OPEN. Using the lemma’s and ,
where is used in the first term, admissibility in the second, and lies on an optimal path, . Termination follows as in A*: OPEN’s values cannot remain below indefinitely with costs and finite branching.
∎In practice almost nobody reopens: if is consistent, WA* without reopening closed nodes still satisfies (Likhachev, Gordon and Thrun prove this in the ARA* paper, 2003), avoiding re-expansions. This is the version used in the next figure.
gen_wastar.py in this lesson's interactive folder.Two lessons emerge from the figure. First, the bound is almost never reached. With mean cost is 1.156 times optimal and the worst of 200 cases 1.615; with , 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 save the most. Going from to 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 you pay much quality for little time.
Beware a counterintuitive consequence: increasing does not always reduce nodes on a particular instance. On the first instance in the set, expands 2797 nodes and , 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 , then , 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 has decreased since it was last expanded has not yet propagated that improvement to successors.
- Each search (
ImprovePath) is WA* without reopening with . If the of an already closed state decreases, it is not reopened: it is recorded in an INCONS list. - When a search ends, lower , move INCONS states to OPEN, reorder OPEN with the new , empty CLOSED and search again. The entire already calculated tree is preserved: only inconsistent nodes are re-expanded.
ImprovePathstops when , not when it removes the goal (the goal may not re-enter OPEN).
Besides bound , ARA* calculates a tighter a posteriori bound,
because the numerator is the cost of the solution at hand and the denominator, the smallest unweighted 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 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 block are walls). Movement is in 8 directions, with cost 1 horizontally and vertically and diagonally, without cutting corners; the heuristic is octile distance, consistent for that movement model.
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 , 30% of those expansions suffice and the path is 2.3% longer; with , 16% of expansions and 8% longer. Again, the bounds (50% and 200% longer) are far away.
Now ARA*, with weight sequence , compared against repeating weighted A* from scratch at each weight.
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)")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 (, much better than bound ). Searches with and expand nothing: the stopping condition already holds with the same OPEN. With the path improves to 1% and with reaches optimal, with 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 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 and , expand and states, each nearly as many as a complete A*. With 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 projects to a path in that is no more expensive. This suffices for everything we need, as you will prove in a guided exercise: is admissible and consistent. The previous lesson’s relaxation is the case of identity with more or cheaper edges; abstraction also merges states.
In the 15-puzzle, the abstraction of a pattern (a set of tiles) erases the identity of the others: an abstract state is the position of 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 tiles has states rather than , and for there are : 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 tiles is a tuple of distinct cells from (with ): an -permutation of elements, and there are (permutations without repetition). The optimal table has exactly entries, and we need a quickly computed bijection between -permutations and . The natural one is lexicographic position:
Factor counts how many still-free cells are smaller than : how many lexicographically earlier choices existed at position , each leaving ways to complete the rest. For and , the multipliers are , , , and . 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 , which uses only bit shifts but wastes combinations with repeated cells: entries for 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 if move moves a tile in 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 . Abstraction with costs satisfies condition 1 of the abstraction definition, so is admissible and consistent with respect to : and for every path from to the goal. Summing over , , and for optimal path , .
∎The proof uses disjointness at a single point, : 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.
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 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 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.
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]))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")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 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?
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_dictitertools.permutations generates 5-permutations in exact lexicographic order, so array entry and the -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.
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")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 by 2 to 6 moves relative to Manhattan in four of five instances, and since nodes grow exponentially with , this translates to factors of 10 to 80 in the three compared by the cell. In the fourth, the PDB does not increase (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.
| Heuristic | Mean | Generated nodes (mean) | Seconds | Memory |
|---|---|---|---|---|
| Manhattan | 36.940 | 401 189 630 | 53 | 0 |
| Additive PDB 5-5-5 | 41.560 | 3 090 405 | 0.540 | 3 145 kB |
| Additive PDB 6-6-3 | 42.924 | 617 555 | 0.163 | 33 554 kB |
| Additive PDB 7-8 | 45.630 | 36 710 | 0.028 | 576 575 kB |
Every move of mean 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 , 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 states (values 0 to 11 stored in 4 bits: 44 089 920 bytes, mean 8.764), and two groups of 6 edges, with states each (mean 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 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 . With a heuristic the story was worse: classical bidirectional algorithms guided by 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 with (estimating distance to the goal) and backward from the goal with (estimating distance to ), always expanding the node of least priority
Term is key: a node more than from its origin has , while optimal-path nodes near each end have , so they are expanded first. If is the cost of the best solution found (whenever one side generates a node open on the other), MM stops when
where is the minimum priority of the two OPEN sets and the cheapest edge cost. The authors prove that with admissible , MM returns , never expands a node with and its forward (backward) search never expands a state more than from the start (goal). MM0 is the case.
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 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 . 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).
| Situation | Choice | Why |
|---|---|---|
| Huge space, few transpositions (puzzles, Rubik), integer costs | IDA* | memory, few iterations, no memory management |
| Same case, but free memory and many queries with the same goal | IDA* + 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 limit | IDA* would re-explore equivalent paths exponentially many times |
| Real costs, linear memory required | IDA* with minimum jump , or RBFS | avoid iterations; with , cost |
| Immediate answer and quality guarantee needed | Weighted A* with between 1.2 and 2 | most savings come from the first increases in |
| Unknown time, interruptible | ARA* | increasingly better solutions with bound , reusing work |
| One isolated query between distant points, good heuristic | A*; try MM if most of A*‘s expansions are far from the start | MM does not go beyond on each side |
Common mistakes
Exercises
Step 1 of 4. What fact about OPEN do you need?
Step 1 of 4. How do you prove admissibility?
rank(perm, n) and unrank(r, n, k) for -permutations of in lexicographic order: rank takes a tuple of distinct elements and returns its position in , 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()Summary
- IDA* repeats depth-first searches with threshold ; the next threshold is the smallest pruned . It is optimal with admissible and uses memory. With integer costs it takes at most iterations (half with Manhattan, by parity); with real costs it may take one per node, and a minimum jump fixes this at the price of . It does not detect transpositions.
- RBFS stores the backed-up value of each alternative and uses memory; SMA* uses all available memory by discarding the worst leaf.
- Weighted A*, , guarantees ; in practice overhead is much smaller than the bound and the first increases give almost all the savings.
- ARA* lowers while reusing search (OPEN and INCONS), publishing at each step an a posteriori bound tighter than .
- 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 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 , is heuristic bidirectional search guaranteed not to pass in either direction.