A* and the theory of admissible heuristics
Informed search uses an estimate h(n) of remaining cost to guide exploration. Prove A* optimality with admissible and consistent heuristics, study its optimal efficiency, design heuristics using relaxed problems and measure their quality with effective branching factor.
After this lesson you can
- Prove A* optimality with admissible heuristics in trees and consistent heuristics in graphs.
- Design admissible heuristics through systematic relaxation of problem rules.
- Compare heuristics by dominance and measure quality with effective branching factor.
- Implement A* with a priority queue, tie-breaking and node reopening, and diagnose inconsistency failures.
- Explain which nodes A* certainly expands and in what sense it is optimally efficient.
Before you start
Motivation: searching with a compass
The previous lesson’s uniform-cost search is optimal and complete, but blind: it expands states in order of distance from the start, in all directions at once, without knowing where the goal is. On a map this means exploring an entire disk around the starting point to reach a point on its boundary. In a puzzle it means exploring every state closer than the solution, and their number grows exponentially with depth.
The 8-puzzle, our test bed throughout the lesson, makes this clear. It has reachable states and its optimal solutions take up to 31 moves. Its larger sibling, the 15-puzzle, has . On instances with optimal solutions of 10 moves, uniform-cost expands 597 nodes on average; A* with the Manhattan heuristic, 14.5. You will measure this yourself below.
The idea that changes everything is small: in addition to the cost already paid , use an estimate of the remaining cost, , to decide what to expand. The hard question is not how to use it, but what conditions it must satisfy for the result to remain optimal, how much work it saves and where it comes from. This lesson addresses those questions:
- Routes. Route planners and video games calculate paths on road graphs or grids with a geometric heuristic (straight-line distance).
- Puzzles and planning. In the 8-puzzle, Rubik’s cube or automated planning, the heuristic comes from solving a simplified version of the problem. This is the central idea of the lesson.
- Robotics. On occupancy grids, A* and its variants plan robot and car movements. Hybrid A* (Dolgov, Thrun, Montemerlo and Diebel, IJRR 2010) was validated at the 2007 DARPA Urban Challenge.
- Learning. A heuristic is an estimate of cost to go. Reinforcement learning’s value functions generalize the idea and can be learned. AlphaZero, which you will encounter in this module, combines search with a learned value estimate.
Greedy best-first search
Every search in this lesson is an instance of best-first search: the previous lesson’s graph search with the frontier ordered by an evaluation function . Uniform-cost uses . The most aggressive choice is the opposite: forget the cost paid and trust only the estimate.
On a map without obstacles, using straight-line distance as , greedy search goes straight to the goal and expands very few nodes. But it has two defects worth understanding precisely:
- It is not optimal. It ignores what it has spent, so it selects the successor that looks closest to the goal even if reaching it is costly or ends in a detour. In graph search on the 8-puzzle with Manhattan, the paths it returns are much longer than optimal: for instances of optimal depth 24, 48.2 moves on average.
- It is not complete as tree search. Without an explored set it may get trapped in a cycle. Take a state with whose successors are , with , and , with ; the goal is reachable only through , and only leads back to . Greedy tree search expands , then (smallest ), generates again with , expands it, returns to … and the copy of waits forever. As graph search on a finite graph it is complete, because each state is expanded at most once.
Greedy search is not always faster either. The implementation cell measures that, with Manhattan, on depth-10 instances it expands 30.6 nodes on average versus 14.5 for A*; its advantage appears only on deep instances, where A* pays to guarantee optimality (at depth 24, 327.7 versus 817.6).
A*: add what was paid and what remains
estimates the total cost of the best path through . With , A* is uniform-cost, that is, Dijkstra stopping at the goal (Dijkstra’s algorithm). With , the frontier always has a node on an optimal path at its head and, with suitable tie-breaking, A* goes straight to the goal without deviation. Everything interesting lies between the extremes.
A*, Dijkstra and greedy search differ only in their priority function, and it is useful to see them as points in a family. With , weight gives Dijkstra, gives A*, and behaves like greedy search.
Three things the figure teaches and the rest of the lesson proves:
- Cells with small are expanded first, and contours are level surfaces of . With , and the contours are balls in the grid metric. With , the expanded region consists of those with below optimal cost, hugging the path more tightly the better is.
- With the cost is always optimal and with it may not be, although it never exceeds times the optimum. This is weighted A* (Pohl, 1970), which you will study next lesson as bounded suboptimal search.
- Tie-breaking matters. In the open room there are many optimal paths and all their cells have the same . For equal , if the larger (farthest advanced) is preferred, A* goes straight; if the smaller is preferred, it traverses almost the entire plateau.
The algorithm and its details
A*(inicio):
g[inicio] ← 0; frontera ← {inicio con prioridad (h(inicio), 0)}
mientras la frontera no esté vacía:
n ← extraer el de menor (f, −g) ▹ a igual f, el de mayor g
si la entrada es obsoleta (su g > g[n]): continuar
si n es meta: devolver el camino por padre[·] ▹ test al EXTRAER
cerrar n
para cada sucesor n' con coste c:
si g[n] + c < g[n']:
si n' está cerrado:
si no se permite reabrir: continuar
reabrir n'
g[n'] ← g[n] + c; padre[n'] ← n
insertar n' con prioridad (g[n'] + h(n'), −g[n'])
devolver fallo
Four implementation decisions have theoretical consequences:
- Priority queue with lazy deletion.
heapqdoes not permit decreasing an element’s priority, so when improves a new entry is inserted and the old one is discarded when removed. This is the same as Dijkstra. - Goal test on removal. Generating the goal only proves a path exists; removing it proves, as we will see, that no cheaper path exists. It is the first common mistake in the final list.
- Reopening. If a closed node receives a better , it can be reopened (returned to the frontier) or ignored. With consistent heuristics this never happens; with merely admissible heuristics, ignoring it costs optimality.
- Tie-breaking. For equal , preferring the larger (equivalently, the smaller ) advances in depth across the plateau and is the usual rule.
Admissibility: optimality in tree search
An admissible heuristic is optimistic: the real path is never cheaper than it says. Straight-line distance is admissible on any map because no path is shorter than the segment. The name comes from Hart, Nilsson and Raphael: an algorithm is admissible if it guarantees an optimal solution, and the condition on makes A* admissible.
Proof
Fix an optimal path from start to goal , costing .
Invariant. While A* has not terminated, the frontier contains a node on with , the cost from to it. We prove this by induction on the number of expansions. Initially the frontier is and . If a node other than that is expanded, remains in the frontier. If is expanded and is not the goal, is generated with and enters the frontier. In tree search each path is a distinct node, so nothing can discard it.
No suboptimal goal node is removed. Suppose, for a contradiction, that a goal with is removed. Since , . But at that moment the frontier contains the invariant’s , with
where the inequality is admissibility and the final equality follows because lies on an optimal path. Thus and A* would have removed first. Contradiction.
Termination. Every node removed before the optimal goal has by the same argument, hence . With costs of at least , these nodes are paths of at most actions, and finite branching makes their number finite. While no goal is removed, eventually the invariant’s is expanded and index advances; after finitely many steps a goal is removed, which by the preceding argument is optimal.
∎The assumptions matter. Without there can be infinitely many bounded-cost paths (a chain with costs ) and A* does not terminate. With inadmissible the argument fails at inequality , and indeed a single node on an optimal path with too large is enough for A* to remove a worse goal first.
Consistency: optimality in graph search
Graph search stores each state only once, breaking the previous invariant: if state on an optimal path was closed earlier with a worse , the better route to it never re-enters the frontier. A stronger, local condition is needed.
This is a triangle inequality: the estimate from cannot exceed the cost of one step plus the estimate from where that step lands. Every geometric distance satisfies it and, as we will see, so does every heuristic from a relaxed problem.
Two immediate consequences, which you will prove in the guided exercise: a consistent heuristic is admissible, and along any path the values do not decrease, because a step increases by and decreases by at most that amount. The converse is false: in the next figure’s graph, , and is admissible () but violates the inequality.
A* with a consistent heuristic is Dijkstra with different weights
The cleanest way to see why consistency suffices uses Johnson reweighting. Define reduced costs
Consistency is exactly . Along a path from start to , the terms cancel in a chain (telescoping sum), and
For fixed , term is the same for all paths, so shortest paths under and coincide. And reduced distance to node is : Dijkstra on removes nodes in exactly the order , the A* order. Since Dijkstra with nonnegative weights closes each node at its final distance, we obtain the central result:
Reduced costs also give an intuition that will recur: with a perfect heuristic, , every edge on an optimal path has reduced cost 0 and search advances without paying anything along the good path; any detour costs. In reinforcement learning, adding a potential difference to reward is the same transformation and likewise does not change optimal policies: this is potential-based reward shaping.
In the guided exercise you will give a direct proof of the theorem without going through Dijkstra.
Admissible but inconsistent
What if is admissible but inconsistent? In a tree nothing bad happens, by the first theorem. In a graph, a node may be removed with an worse than optimal, because the node leading to it along the good path has such a large that it waits in the frontier. If the good path appears later, the node is already closed.
With the initial heuristic, , , and . A* expands and the frontier contains (), () and (). It removes with , closes it and generates with . Then, from and , with , it removes first (greater ) and then , which discovers path of cost 2. But is closed. Without reopening, the next removal is with . With reopening, returns to the frontier with , , and the goal leaves with .
The remedy guaranteeing optimality is reopening: the first theorem adapts and A* becomes optimal again, at the cost of expanding some nodes several times. A frequently cited trick, pathmax, is not sufficient by itself. It uses, when generating from , (Mérő, 1984, proposed it along with a second rule propagating values to the parent), and makes nondecreasing along the path by which each node is generated. But it does not make the heuristic consistent: in the figure, when generates , pathmax gives it , and was already closed with ; without reopening the error is the same. Holte (2010) lists “pathmax makes any admissible heuristic consistent” among common heuristic-search mistakes. Reopening is not free either, as you will see at the end.
Which nodes A* expands: contours and optimal efficiency
The graph theorem says more than “A* is optimal”: it says which nodes it expands. Let be the value with which would be removed if reached by its best path.
Proof
By the previous theorem, A* removes nodes in nondecreasing order of , each with and thus , and the optimal goal leaves with .
(1) Let have and let be an optimal path to it. By monotonicity of along paths, every satisfies . While has not been expanded, the frontier contains the first unclosed with (its predecessor is closed with its optimal ), that is, with . Since the goal is removed with , all those are removed first, in particular .
(2) If , any entry for in the frontier has , while until the end the frontier contains a node on an optimal path to the goal with . The goal leaves before .
∎Thus A* with a consistent heuristic expands the entire “ball,” part of its boundary and nothing outside. This is what the first figure’s “relative to ” mode shows: with , every aqua cell has an expanded marker, no gray one does, and among the orange plateau cells more or fewer are expanded depending on tie-breaking. In the open room, with tie-breaking by smaller , almost the entire plateau is traversed.
Could another algorithm do better? Dechter and Pearl (1985) formalized the question carefully. They consider algorithms that, like A*, guarantee an optimal solution whenever is admissible and access the problem only by expanding nodes and querying .
The first part uses an adversarial argument. Suppose an algorithm in the class terminates without expanding a node with . Construct an identical instance except that has a new successor, a goal , with and . The heuristic remains consistent (the new edge satisfies ), and the new optimal solution costs . Since never expanded , it cannot distinguish the two instances: it does the same on both and returns a solution costing on the second, which is no longer optimal. This contradicts being in the class.
The final qualification matters: this optimality concerns expansions with . Those on the plateau depend on tie-breaking and, in problems such as the open room, are the majority.
Designing heuristics: relaxed problems
Where do admissible heuristics come from? The systematic answer is the optimal cost of an easier problem.
Proof
The relaxed problem’s state graph contains every edge of the original at equal or lower cost. Every original path is a relaxed path of no greater cost, so . And is a graph distance: if is an original action, it is also a relaxed action, and the triangle inequality for distances gives .
∎The trick is choosing relaxations whose optimal cost can be calculated quickly, ideally with a formula. This is the same idea as convex relaxations and the dual function in optimization: removing constraints gives an optimistic lower bound on the optimum. In automated planning the principle is fully mechanized: delete relaxation is obtained without human intervention from the action description language.
The 8-puzzle ladder
Write the 8-puzzle movement rule as a statement with conditions: a tile can move from cell X to cell Y if X is adjacent to Y and Y is empty (following Russell and Norvig). Removing conditions gives three relaxations:
- Without “empty”: a tile moves to any adjacent cell, even if occupied. Tiles no longer obstruct one another, each travels alone to its place and the optimal cost is the sum of their row and column distances: Manhattan distance.
- Without “adjacent”: a tile can jump to the blank wherever it is. The optimal cost is sorting a permutation by repeatedly swapping the blank with a tile: Gaschnig’s heuristic (1979). It is computed by a greedy loop (if the blank occupies a tile’s cell, move that tile there; if it is in its own place, move it to a misplaced tile) and equals the number of misplaced tiles plus the number of permutation cycles not containing the blank, because the blank must enter each such cycle with a move that places no tile.
- Without both: each tile jumps to its place in one move. The optimal cost is the number of misplaced tiles.
Each relaxation retaining one more rule gives an equal or larger heuristic, because the relaxed problem has fewer actions. But Manhattan and Gaschnig retain different rules and are incomparable: among 181 440 states, Manhattan is larger in 177 591 and Gaschnig in 304. The weaker relaxation winning on a few states is not merely a curiosity: it says Gaschnig captures something (permutation cycles) that Manhattan cannot see.
Critiquing the relaxation: linear conflicts
Manhattan loses information because it lets tiles pass through each other. If two tiles are in their goal row but in reverse order, for example and in the top row with on the left, one must leave the row and return: two vertical moves Manhattan does not count. Hansson, Mayer and Yung (1992) turned this observation into the linear conflicts heuristic: Manhattan plus 2 for each tile that must be moved out of its row or column so the remaining ones are ordered.
Be careful with the count. Counting 2 per inverted pair overestimates: in a line with three tiles in reverse order there are three conflicting pairs, but removing two tiles suffices. In the 8-puzzle, the version adding 2 per pair overestimates on some deep states; the correct one, computing the minimum number of tiles to remove, is admissible and consistent across all 181 440 states (as the implementation cells check). Checking this on the 8-puzzle is not a general proof; Hansson, Mayer and Yung’s argument is: extra moves for a row conflict are vertical and made by tiles already in their goal row (Manhattan counts no vertical moves for them), column-conflict moves are horizontal by tiles in their goal column, and these are distinct moves. In the coding exercise you will generalize this to boards, where the minimum number of tiles to remove follows from the longest increasing subsequence.
Comparing heuristics: dominance
Proof
The nodes A* certainly expands with are those with . If , then .
∎This is a guarantee about sets, not times: the plateau may change either way, and a heuristic more expensive to compute may win in nodes and lose in seconds. You will measure it.
When neither dominates, combine them. If are admissible, is admissible (each term is) and dominates all of them; if all are consistent, their maximum is too, because for each . In the 8-puzzle, exceeds Manhattan in those 304 states. Adding, by contrast, is valid only when heuristics count disjoint costs: if and measure the same thing, can reach . The next lesson’s additive pattern databases achieve admissible sums by distributing each move’s cost among heuristics.
Measuring: effective branching factor
Comparing heuristics by expanded nodes on particular instances is cumbersome: the number grows exponentially with depth and instances of different lengths cannot be compared. We need one number per heuristic.
The right-hand side is strictly increasing in and equals at , so for there is a unique positive root, computed by bisection. With (a perfect heuristic with good tie-breaking, expanding only the nodes on the path) it gives ; the closer to 1, the better the heuristic. Some authors count generated rather than expanded nodes; what matters is using the same convention throughout a comparison.
The implementation cell’s table reproduces the classic experiment: 10 instances per depth, mean expanded nodes and . For , misplaced tiles give , Gaschnig , Manhattan and linear conflicts . The order respects dominance, and the difference grows with depth: at , Manhattan expands 197.4 nodes on average and misplaced tiles 1060.1.
is not a perfect constant either. In the data it grows with at small depths and stabilizes: Manhattan gives , , and for , , and .
Relative error
What determines ? Classic analysis (Pearl, 1984; Russell and Norvig summarize it in chapter 3) measures the quality of by its error. With constant relative error , in a space with one goal and reversible actions, expanded nodes grow as , where is the space’s branching factor: A* behaves like blind search whose effective depth is only the fraction of the path the heuristic cannot see. In terms of , this is . The consequence is harsh: unless error grows at most logarithmically with , A* remains exponential. A heuristic that gets 70% of the cost right does not eliminate the explosion; it tames it.
The implementation cell checks this. It computes mean on the initial states and the implied , . For Manhattan and linear conflicts, between and , the implied lies between 1.54 and 1.82: it is not constant, but the two heuristics, with different errors, are compatible with the same space growth. The model explains order and scale well; exact constancy requires its assumptions (uniform relative error at all nodes), which do not hold here.
Inconsistent heuristics: re-expansions and Martelli’s worst case
If almost all natural heuristics are consistent in practice (Pearl observed this in 1984, and the five 8-puzzle heuristics confirm it), why worry? Because useful heuristics exist that are not: those randomly queried among several tables, those using problem symmetries, or those from databases with missing or compressed values (Zahavi, Felner, Schaeffer and Sturtevant, 2007).
With reopening, A* remains optimal with an admissible heuristic but may expand the same node many times. How many? Martelli (1977) constructed a graph family with nodes where A* needs expansions, and proposed a variant, algorithm B, with worst case (according to the survey by Zhang, Sturtevant, Holte, Schaeffer and Felner, 2009).
The implementation cell uses a family constructed on the same idea. Nodes are (start), (goal), with an edge for every . Skipping node costs extra, so the unique optimal path visits them all in order; and every intermediate has , admissible but so large relative to lower-index nodes that is not expanded until everything below it has been explored with a worse . When it is finally expanded, it improves for all lower nodes, which reopen and are explored again in the same pattern. The removal order for is : the “ruler” sequence of a binary counter. Expansions number exactly for distinct nodes expanded: for , 2048 expansions and 2036 reopenings. Without reopening, search performs only expansions but returns a suboptimal path.
The exponential worst case requires edge weights and values to grow exponentially with graph size, as here. Zhang and coauthors (2009) prove this with a counting argument: with integer weights, every path cost is a multiple of their greatest common divisor , so each reopening lowers the node’s by at least ; many reopenings of one node require some to be enormous. Thus if weights are bounded by a constant independent of graph size, A* with an inconsistent heuristic performs at most expansions, just like algorithm B. Their experiments conclude that inconsistent heuristics are not as bad for A* as believed and the worst case is unlikely in practice. In the figure’s graph, choose the exponential family and enable reopening: the player shows being expanded repeatedly.
Implementation from scratch
First, generic A*: it receives the initial state, a goal test, a successor function and a heuristic, and returns the path, its cost and the expansion count. The priority tuple (f, -g, orden, estado) implements tie-breaking by larger and, if tied, arrival order.
import heapq
import itertools
def astar(inicio, es_meta, sucesores, h, reabrir=True):
"""A* en grafo. sucesores(s) da pares (s2, coste). Devuelve (camino, coste, estadísticas)."""
g = {inicio: 0}
padre = {inicio: None}
orden = itertools.count() # tercer criterio: FIFO
frontera = [(h(inicio), 0, next(orden), inicio)] # (f, -g, orden, estado): a igual f, mayor g
cerrados = set()
est = {"expandidos": 0, "generados": 1, "reaperturas": 0}
while frontera:
f, menos_g, _, s = heapq.heappop(frontera)
if -menos_g > g[s]: # entrada obsoleta: ya hay un camino mejor a s
continue
if es_meta(s): # test de meta al EXTRAER, no al generar
camino = []
while s is not None:
camino.append(s)
s = padre[s]
return camino[::-1], -menos_g, est
cerrados.add(s)
est["expandidos"] += 1
for s2, c in sucesores(s):
g2 = g[s] + c
if g2 < g.get(s2, float("inf")):
if s2 in cerrados:
if not reabrir:
continue # sin reapertura: el camino mejor se ignora
cerrados.discard(s2)
est["reaperturas"] += 1
g[s2] = g2
padre[s2] = s
est["generados"] += 1
heapq.heappush(frontera, (g2 + h(s2), -g2, next(orden), s2))
return None, float("inf"), est
# Un grafo pequeño con una heurística admisible pero inconsistente (la del interactivo «Rompe la consistencia»)
aristas = [("S", "A", 1), ("S", "C", 3), ("A", "C", 1), ("C", "G", 3), ("S", "B", 2), ("B", "G", 5)]
vecinos = {}
for u, v, c in aristas:
vecinos.setdefault(u, []).append((v, c))
vecinos.setdefault(v, []).append((u, c))
h_inc = {"S": 3, "A": 4, "B": 3, "C": 0, "G": 0}.get
for reabrir in (False, True):
camino, coste, est = astar("S", lambda s: s == "G", lambda s: vecinos[s], h_inc, reabrir)
print(f"reabrir={reabrir!s:5} camino={'-'.join(camino)} coste={coste} {est}")
# El error de parar al GENERAR la meta
def parar_al_generar(inicio, meta, sucesores, h):
frontera = [(h(inicio), 0, inicio)]
g = {inicio: 0}
while frontera:
_, _, s = heapq.heappop(frontera)
for s2, c in sucesores(s):
if s2 == meta:
return g[s] + c # ¡demasiado pronto!
if g[s] + c < g.get(s2, float("inf")):
g[s2] = g[s] + c
heapq.heappush(frontera, (g[s2] + h(s2), -g[s2], s2))
atajo = {"S": [("G", 10), ("A", 1)], "A": [("G", 1)], "G": []}
print("parando al generar:", parar_al_generar("S", "G", lambda s: atajo[s], lambda s: 0))
print("parando al extraer:", astar("S", lambda s: s == "G", lambda s: atajo[s], lambda s: 0)[1])The output reproduces the figure: without reopening, cost 6 via ; with it, cost 5 via and one reopening. The shortcut shows the first common mistake: the direct edge costing 10 generates the goal in the first step, but the path through costs 2.
The 8-puzzle and its heuristics
The state is a tuple of 9 integers, with 0 for the blank. The five heuristics, and exact for all states by breadth-first search from the goal (moves are reversible, so distance from the goal is distance to it).
from collections import deque
import random
META = (1, 2, 3, 4, 5, 6, 7, 8, 0) # 0 es el hueco
DESTINO = {t: divmod(i, 3) for i, t in enumerate(META)}
ADY = [[j for j in range(9) if abs(i // 3 - j // 3) + abs(i % 3 - j % 3) == 1] for i in range(9)]
def sucesores_puzzle(s):
b = s.index(0)
for j in ADY[b]:
t = list(s)
t[b], t[j] = t[j], 0
yield tuple(t), 1
def h_cero(s):
return 0
def h_descolocadas(s): # sin «adyacente» y sin «vacía»: cada ficha salta a su sitio en 1 movimiento
return sum(1 for i, t in enumerate(s) if t and t != META[i])
def h_manhattan(s): # sin «vacía»: cada ficha camina sola hasta su sitio
d = 0
for i, t in enumerate(s):
if t:
f, c = divmod(i, 3)
fm, cm = DESTINO[t]
d += abs(f - fm) + abs(c - cm)
return d
def h_gaschnig(s): # sin «adyacente»: una ficha puede saltar al hueco esté donde esté
s, n = list(s), 0
while s != list(META):
b = s.index(0)
if META[b]: # el hueco ocupa la casilla de otra ficha: llévala allí
j = s.index(META[b])
else: # el hueco está en su sitio: sácalo hacia una ficha mal colocada
j = next(k for k in range(9) if s[k] != META[k])
s[b], s[j] = s[j], 0
n += 1
return n
def h_conflictos(s): # Manhattan + 2 por cada ficha que hay que sacar de su línea (filas y columnas)
extra = 0
for eje in (0, 1): # 0: filas, 1: columnas
for linea in range(3):
casillas = [linea * 3 + k for k in range(3)] if eje == 0 else [k * 3 + linea for k in range(3)]
orden = [DESTINO[s[i]][1 - eje] for i in casillas if s[i] and DESTINO[s[i]][eje] == linea]
pares = sum(1 for a in range(len(orden)) for b in range(a + 1, len(orden)) if orden[a] > orden[b])
extra += 2 * (0, 1, 1, 2)[pares] # con 3 fichas: 1 o 2 pares se arreglan sacando 1; 3 pares, sacando 2
return h_manhattan(s) + extra
# Distancias exactas h* de los 181 440 estados alcanzables, por BFS desde la meta (los movimientos son reversibles)
dist = {META: 0}
cola = deque([META])
while cola:
s = cola.popleft()
for t, _ in sucesores_puzzle(s):
if t not in dist:
dist[t] = dist[s] + 1
cola.append(t)
print("estados alcanzables:", len(dist), " profundidad máxima:", max(dist.values()))
HEUR = {"h=0": h_cero, "descolocadas": h_descolocadas, "Gaschnig": h_gaschnig,
"Manhattan": h_manhattan, "conflictos": h_conflictos}
# Admisibilidad y consistencia en una muestra de 2000 estados (la celda siguiente cubre todo el espacio)
muestra = random.Random(0).sample(sorted(dist), 2000)
for nombre, h in HEUR.items():
sobre = sum(h(s) > dist[s] for s in muestra)
incons = sum(h(s) > 1 + h(t) for s in muestra for t, _ in sucesores_puzzle(s))
media = sum(h(s) / dist[s] for s in muestra if dist[s]) / sum(1 for s in muestra if dist[s])
print(f"{nombre:13s} sobreestima en {sobre} estados, aristas inconsistentes: {incons}, h/h* medio = {media:.3f}")With three tiles in a line, rule (0, 1, 1, 2)[pares] gives the minimum number to remove: if there are 1 or 2 inverted pairs, removing one tile suffices; if 3, the line is reversed and two are needed. None of the five overestimates or violates consistency in the sample. To assert this over the entire space, the next cell computes all five heuristics at once across 181 440 states with NumPy and checks the triangle inequality on every move.
import numpy as np
# Las cinco heurísticas, vectorizadas, sobre los 181 440 estados a la vez
E = np.array(list(dist.keys()), dtype=np.int8) # una fila por estado: la ficha de cada casilla
hstar = np.array(list(dist.values()))
fila_m = np.array([DESTINO[t][0] for t in range(9)]) # fila y columna de destino de cada ficha
col_m = np.array([DESTINO[t][1] for t in range(9)])
fila_c, col_c = np.divmod(np.arange(9), 3)
ficha = E > 0
H = {"h=0": np.zeros(len(E), dtype=int)}
H["descolocadas"] = (ficha & (E != np.array(META))).sum(1)
H["Manhattan"] = (ficha * (abs(fila_c - fila_m[E]) + abs(col_c - col_m[E]))).sum(1)
# Gaschnig = descolocadas + ciclos de la permutación casilla -> casilla de destino que no pasan por el hueco
destino_casilla = np.array([META.index(t) for t in range(9)])[E] # p[i]: casilla meta de la ficha que está en i
minimo, cur = np.tile(np.arange(9), (len(E), 1)), np.tile(np.arange(9), (len(E), 1))
con_hueco = E == 0
for _ in range(9): # recorre cada ciclo: mínimo y si contiene el hueco
cur = np.take_along_axis(destino_casilla, cur, 1)
minimo = np.minimum(minimo, cur)
con_hueco |= np.take_along_axis(E, cur, 1) == 0
lider = (minimo == np.arange(9)) & (destino_casilla != np.arange(9)) # un representante por ciclo no trivial
H["Gaschnig"] = H["descolocadas"] + (lider & ~con_hueco).sum(1)
extra = np.zeros(len(E), dtype=int)
for eje, (pos_c, dest_eje, dest_otro) in enumerate([(fila_c, fila_m, col_m), (col_c, col_m, fila_m)]):
for linea in range(3):
cas = np.where(pos_c == linea)[0] # las 3 casillas de la línea, en orden
t = E[:, cas]
en_linea = (t > 0) & (dest_eje[t] == linea)
o = dest_otro[t]
pares = sum(en_linea[:, a] & en_linea[:, b] & (o[:, a] > o[:, b]) for a in range(3) for b in range(a + 1, 3))
extra += 2 * np.array([0, 1, 1, 2])[pares]
H["conflictos"] = H["Manhattan"] + extra
ok = all(np.array_equal(H[n][:2000], [HEUR[n](tuple(s)) for s in E[:2000]]) for n in HEUR)
print("coinciden con las funciones de la celda anterior en 2000 estados:", ok)
print("estados donde alguna sobreestima:", {n: int((v > hstar).sum()) for n, v in H.items()})
nz = hstar > 0
print("h/h* medio:", {n: round(float((v[nz] / hstar[nz]).mean()), 3) for n, v in H.items()})
for a, b in [("Gaschnig", "descolocadas"), ("Manhattan", "descolocadas"), ("Manhattan", "Gaschnig"),
("conflictos", "Manhattan"), ("conflictos", "Gaschnig")]:
print(f"{a} > {b}: {int((H[a] > H[b]).sum()):6d} estados {a} < {b}: {int((H[a] < H[b]).sum()):6d}")
m = np.maximum(H["Manhattan"], H["Gaschnig"])
print("máx(Manhattan, Gaschnig) > Manhattan en", int((m > H["Manhattan"]).sum()), "estados")
# Consistencia en TODAS las aristas: h(s) <= 1 + h(t) para cada movimiento s -> t.
# Cada estado se codifica como un entero en base 9; el vecino se localiza con searchsorted.
pot = 9 ** np.arange(9, dtype=np.int64)
codigo = E.astype(np.int64) @ pot
orden_c = np.argsort(codigo)
hueco = (E == 0).argmax(1)
violaciones, aristas_dirigidas = {n: 0 for n in H}, 0
for b in range(9):
filas = np.where(hueco == b)[0]
for j in ADY[b]: # el hueco va de b a j y la ficha t de j a b
t = E[filas, j].astype(np.int64)
vecino = orden_c[np.searchsorted(codigo, codigo[filas] - t * pot[j] + t * pot[b], sorter=orden_c)]
aristas_dirigidas += len(filas)
for n, v in H.items():
violaciones[n] += int((v[filas] > 1 + v[vecino]).sum())
print("aristas dirigidas comprobadas:", aristas_dirigidas, " violaciones de la consistencia:", violaciones)All five are admissible and consistent throughout the space: none violates on any move. The dominance ladder is exact: Gaschnig and Manhattan dominate misplaced tiles, neither dominates the other, and linear conflicts dominate Manhattan (strictly on 80 040 states) and, in this puzzle, Gaschnig as well. On average, Manhattan recovers 64.2% of exact cost, linear conflicts 69.2%, and Gaschnig and misplaced tiles just 37.4% and 33.1%.
The table of expanded nodes and
Instances are chosen randomly, 10 per optimal depth , among states that BFS places at that distance. Uniform-cost () runs only up to to avoid taking too long.
def b_efectivo(N, d, tol=1e-10):
"""Raíz b* > 0 de N + 1 = 1 + b + b^2 + ... + b^d, por bisección (el lado derecho crece con b)."""
lo, hi = 0.0, max(1.0, float(N))
while hi - lo > tol:
m = (lo + hi) / 2
if sum(m ** i for i in range(d + 1)) < N + 1:
lo = m
else:
hi = m
return (lo + hi) / 2
# 10 instancias por profundidad óptima d = 6, 8, ..., 24, elegidas al azar entre los estados con dist = d
por_prof = {}
for s, d in dist.items():
por_prof.setdefault(d, []).append(s)
rng = random.Random(2024)
instancias = {d: rng.sample(sorted(por_prof[d]), 10) for d in range(6, 25, 2)}
meta = lambda s: s == META
print(" d " + "".join(f"{n:>21s}" for n in HEUR))
for d in range(6, 19, 2): # hasta 18 en el navegador; 20 a 24, en la figura
fila = f"{d:2d} "
for nombre, h in HEUR.items():
if nombre == "h=0" and d > 10:
fila += f"{'(no se ejecuta)':>21s}"
continue
N = [astar(s, meta, sucesores_puzzle, h)[2]["expandidos"] for s in instancias[d]]
media = sum(N) / len(N)
fila += f"{media:>12.1f} ({b_efectivo(media, d):.3f})"
print(fila)# Más profundo, solo con las dos heurísticas buenas: b* y el error relativo eps = (h* - h)/h* en el estado inicial
print(" d heurística expandidos b* eps medio b*^(1/eps)")
for d in (14, 18, 20, 22, 24):
for nombre in ("Manhattan", "conflictos"):
h = HEUR[nombre]
N = sum(astar(s, meta, sucesores_puzzle, h)[2]["expandidos"] for s in instancias[d]) / 10
eps = sum((d - h(s)) / d for s in instancias[d]) / 10
b = b_efectivo(N, d)
print(f"{d:2d} {nombre:11s} {N:9.1f} {b:.3f} {eps:.3f} {b ** (1 / eps):.2f}")In the first table, at , uniform-cost expands 597.2 nodes () and Manhattan 14.5 (): a factor of 41. In the second, at , linear conflicts expand 368.4 nodes versus 817.6 for Manhattan, with mean relative errors of 0.300 and 0.350. The ladder figure shows all five heuristics up to with the same data.
Greedy search and time
import time
# Voraz primero el mejor: la misma cola, ordenada solo por h
def voraz(inicio, es_meta, sucesores, h):
padre, g = {inicio: None}, {inicio: 0}
orden = itertools.count()
frontera = [(h(inicio), next(orden), inicio)]
expandidos = 0
while frontera:
_, _, s = heapq.heappop(frontera)
if es_meta(s):
return g[s], expandidos
expandidos += 1
for s2, c in sucesores(s):
if s2 not in padre: # búsqueda en grafo: cada estado entra una vez
padre[s2], g[s2] = s, g[s] + c
heapq.heappush(frontera, (h(s2), next(orden), s2))
return None, expandidos
print("Manhattan: voraz frente a A* (media de 10 instancias por profundidad)")
print(" d coste voraz expandidos voraz expandidos A*")
for d in (10, 14, 18, 22, 24):
rv = [voraz(s, meta, sucesores_puzzle, h_manhattan) for s in instancias[d]]
na = sum(astar(s, meta, sucesores_puzzle, h_manhattan)[2]["expandidos"] for s in instancias[d]) / 10
print(f"{d:2d} {sum(c for c, _ in rv) / 10:9.1f} {sum(n for _, n in rv) / 10:12.1f} {na:14.1f}")
# El tiempo no es el número de nodos: coste por evaluación de cada heurística
def cronometra(f, reps=3):
mejor = float("inf")
for _ in range(reps):
t0 = time.perf_counter()
f()
mejor = min(mejor, time.perf_counter() - t0)
return mejor
lote = instancias[20]
print("\nprofundidad 20, 10 instancias:")
for nombre in ("Manhattan", "conflictos"):
h = HEUR[nombre]
nodos = sum(astar(s, meta, sucesores_puzzle, h)[2]["expandidos"] for s in lote)
t_busq = cronometra(lambda: [astar(s, meta, sucesores_puzzle, h) for s in lote], reps=2)
t_eval = cronometra(lambda: [h(s) for s in muestra]) / len(muestra)
print(f" {nombre:11s} {nodos:5d} expandidos {1e6 * t_eval:6.1f} µs por evaluación {1e3 * t_busq:7.1f} ms en total")Greedy returns paths twice the optimal length (48.2 moves on average at ), and its node cost plateaus around 330 from onward, while A* keeps growing: it overtakes greedy at and is 2.5 times greater at . The second part shows the fifth common mistake in action: linear conflicts expand 1598 nodes versus Manhattan’s 3067, nearly half, but each evaluation costs several times more and, in pure Python, total search takes longer. Incremental heuristic computation (one move changes only one row or column) makes each evaluation cheaper and may reverse the balance; the lesson is to measure both.
The exponential family
# Una familia con reexpansiones exponenciales, construida con la idea de Martelli (1977):
# nodos k (inicio), k-1, ..., 1, 0 (meta); arista i -> j para todo i > j.
# Saltarse el nodo l cuesta 2^l de más, así que el único camino óptimo es k, k-1, ..., 0.
def familia(k):
A = {j: 2 ** (k + 2) + j for j in range(1, k + 1)}
A[0] = 0
sucs = {i: [(j, A[i] - A[j] + sum(2 ** l for l in range(j + 1, i))) for j in range(i)] for i in range(k + 1)}
h = {j: 2 ** (j + 2) + j for j in range(1, k)}
h[0] = h[k] = 0
return sucs, h
def h_exacta(sucs, k): # h*(i) por programación dinámica: las aristas bajan de índice
hs = {0: 0}
for i in range(1, k + 1):
hs[i] = min(c + hs[j] for j, c in sucs[i])
return hs
print(" k C* expansiones (con reapertura) coste sin reapertura pares inconsistentes")
for k in range(3, 13):
sucs, h = familia(k)
hs = h_exacta(sucs, k)
assert all(h[i] <= hs[i] for i in h) # admisible
malos = sum(1 for i in sucs for j, c in sucs[i] if h[i] > c + h[j])
_, c1, e1 = astar(k, lambda s: s == 0, lambda s: sucs[s], h.get, reabrir=True)
_, c2, e2 = astar(k, lambda s: s == 0, lambda s: sucs[s], h.get, reabrir=False)
print(f"{k:2d} {hs[k]:6d} {e1['expandidos']:10d} ({e1['reaperturas']} reaperturas) {c2:10d} {malos:6d}")
sucs, h = familia(4)
orden_exp = []
astar(4, lambda s: orden_exp.append(s) or s == 0, lambda s: sucs[s], h.get)
print("\nk = 4, orden en que se extraen los nodos:", orden_exp)
print("aristas:", {i: sucs[i] for i in sucs if sucs[i]})
print("h:", h)The expansions column doubles with each added node, and costs without reopening show the other side: without reopening, A* performs only expansions but returns, for , a path of cost 18 442 when the optimum is 16 396.
The library version: networkx
On explicit graphs there is no need to write A*: networkx.astar_path(G, s, t, heuristic, weight) implements it with a heap, tie-breaking by insertion order and a per-node cache. The heuristic receives the node and goal. In a geometric graph, where weights are Euclidean distances between points, straight-line distance to the goal is consistent by the triangle inequality.
import math
import random
import time
import networkx as nx
# Grafo geométrico aleatorio: n puntos en el cuadrado unidad, arista si están a menos de r; peso = distancia
def grafo_geometrico(n, r, semilla):
rnd = random.Random(semilla)
pos = {i: (rnd.random(), rnd.random()) for i in range(n)}
celdas = {} # cubetas de lado r: solo se comparan puntos vecinos
for i, (x, y) in pos.items():
celdas.setdefault((int(x / r), int(y / r)), []).append(i)
G = nx.Graph()
G.add_nodes_from(pos)
for (cx, cy), pts in celdas.items():
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
for i in pts:
for j in celdas.get((cx + dx, cy + dy), ()):
if i < j and math.dist(pos[i], pos[j]) < r:
G.add_edge(i, j, weight=math.dist(pos[i], pos[j]))
return G, pos
G, pos = grafo_geometrico(3000, 0.035, semilla=7)
gc = G.subgraph(max(nx.connected_components(G), key=len)).copy()
s = min(gc, key=lambda v: pos[v][0] + pos[v][1]) # esquina inferior izquierda
t = max(gc, key=lambda v: pos[v][0] + pos[v][1]) # esquina superior derecha
print(f"componente gigante: {gc.number_of_nodes()} nodos, {gc.number_of_edges()} aristas")
euclid = lambda u: math.dist(pos[u], pos[t]) # admisible y consistente: desigualdad triangular
vec = lambda u: ((v, d["weight"]) for v, d in gc[u].items())
meta_t = lambda u: u == t
res = {}
for nombre, h in (("Dijkstra (h = 0)", lambda u: 0.0), ("A* euclídea", euclid)):
t0 = time.perf_counter()
camino, coste, est = astar(s, meta_t, vec, h)
res[nombre] = (coste, est["expandidos"], time.perf_counter() - t0)
llamadas = []
h_nx = lambda u, v: llamadas.append(u) or math.dist(pos[u], pos[v])
t0 = time.perf_counter()
camino_nx = nx.astar_path(gc, s, t, heuristic=h_nx, weight="weight")
t_nx = time.perf_counter() - t0
coste_nx = nx.path_weight(gc, camino_nx, "weight")
t0 = time.perf_counter()
coste_dij = nx.dijkstra_path_length(gc, s, t)
t_dij = time.perf_counter() - t0
for nombre, (coste, n, seg) in res.items():
print(f"{nombre:18s} coste {coste:.6f} {n:5d} expandidos {1e3 * seg:6.1f} ms")
print(f"{'nx.astar_path':18s} coste {coste_nx:.6f} {len(set(llamadas)):5d} nodos con h evaluada (generados) {1e3 * t_nx:6.1f} ms")
print(f"{'nx.dijkstra':18s} coste {coste_dij:.6f} {1e3 * t_dij:6.1f} ms")
print(f"A* expande el {100 * res['A* euclídea'][1] / res['Dijkstra (h = 0)'][1]:.1f} % de los nodos que expande Dijkstra")All four methods give the same cost. Between the lower-left and upper-right corners, Dijkstra expands 2999 of 3000 nodes (the goal is nearly the farthest point) and A* with Euclidean distance 976: 32.5%. networkx does not report expansions, but counting nodes where it evaluates gives generated nodes: 1196. A*‘s gain here is modest because nodes with occupy an ellipse-like region with foci at the two corners, which covers much of the square between opposite corners. The closer is to straight-line distance, that is, the straighter the graph’s paths, the narrower the region.
Common mistakes
Exercises
Step 1 of 4. What do you induct on?
Step 1 of 4. Let be the node removed at one step, with value . Why does the next removed node have ?
More than one answer may be correct.
More than one answer may be correct.
conflictos_lineales(estado, n) for the sliding puzzle: estado is a tuple of length containing tiles by row and 0 for the blank, and the goal is . Return Manhattan distance plus 2 for each tile that must be removed from its line: in each row (and each column), take tiles in their goal row (column) and count the minimum number to remove so the rest are in goal order. For , a line may have 4 tiles and counting 2 per inverted pair overestimates. Tests check specific values, that it never exceeds optimal cost (computed by BFS), and that it dominates Manhattan.def conflictos_lineales(estado, n):
"""Manhattan + 2 por cada ficha que hay que apartar de su fila o columna de destino."""
h = 0
for i, t in enumerate(estado):
if t:
f, c = divmod(i, n)
fm, cm = divmod(t - 1, n)
h += abs(f - fm) + abs(c - cm)
# tu código: por cada fila y cada columna, el mínimo de fichas a apartar
return hSummary
- Greedy search () is fast on deep problems but is not optimal, and in a tree is not even complete. Dijkstra () is optimal but blind. A* () lies between them, and spans the family.
- Admissibility () suffices for tree-search optimality. Graph search requires consistency (), which implies admissibility and monotonicity of , or reopening nodes.
- A* with a consistent heuristic expands all nodes with , none with , and part of the plateau depending on tie-breaking. By Dechter and Pearl’s adversarial argument, no admissible algorithm with the same heuristic can skip the first group.
- Admissible heuristics come from relaxed problems: in the 8-puzzle, removing “empty” gives Manhattan, removing “adjacent” gives Gaschnig, and removing both gives misplaced tiles. Critiquing the relaxation gives linear conflicts.
- Heuristics are compared by dominance (a partial order; the maximum combines without losing admissibility) and the effective branching factor , which with relative error behaves like : A* tames exponential explosion but does not eliminate it.
- With inconsistent heuristics and reopening, A* remains optimal but may need exponentially many expansions (Martelli), although only with exponentially growing weights and heuristics.