Module contents
Lesson 2 of 23Core 100 min

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 9!/2=181 4409!/2 = 181\,440 reachable states and its optimal solutions take up to 31 moves. Its larger sibling, the 15-puzzle, has 16!/2≈1.05×101316!/2 \approx 1.05\times 10^{13}. 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 g(n)g(n), use an estimate of the remaining cost, h(n)h(n), 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.

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 f(n)f(n). Uniform-cost uses f(n)=g(n)f(n) = g(n). 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 hh, greedy search goes straight to the goal and expands very few nodes. But it has two defects worth understanding precisely:

  1. 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.
  2. It is not complete as tree search. Without an explored set it may get trapped in a cycle. Take a state SS with h(S)=2h(S) = 2 whose successors are AA, with h(A)=1h(A) = 1, and DD, with h(D)=5h(D) = 5; the goal is reachable only through DD, and AA only leads back to SS. Greedy tree search expands SS, then AA (smallest hh), generates SS again with h=2<5h = 2 < 5, expands it, returns to AA… and the copy of DD 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

f(n)f(n) estimates the total cost of the best path through nn. With h=0h = 0, A* is uniform-cost, that is, Dijkstra stopping at the goal (Dijkstra’s algorithm). With h=h∗h = h^*, 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 f=g+w hf = g + w\,h, weight w=0w = 0 gives Dijkstra, w=1w = 1 gives A*, and w→∞w \to \infty behaves like greedy search.

Interactivef contours on a map
200 expanded
  • expanded: darker for larger ff
  • ff contour (band change)
  • frontier
  • returned path
  • start and goal
Tool
1.00
Color by
Tie breaking at equal ff
AlgorithmA* (w = 1)
Expanded cells200 / 200
Cost found33.0
Optimal cost C∗C^*33.0
Cost / C∗C^*1.000
With w≤1w \le 1, heuristic w hw\,h remains admissible and consistent: the cost is optimal and A* (w=1w = 1) expands 200 cells versus 600 for Dijkstra.
An 8-connected grid with cost 1 straight and 1.4 diagonally, without cutting corners, and octile distance as hh (the exact cost if there were no walls). Each expanded cell is colored by its ff (darker for larger values), and lines mark where ff changes bands: these are the ff contours. With w=0w = 0 they are octagons around the start; with w=1w = 1 they stretch toward the goal; with large ww, or in greedy mode, search rushes toward the goal and may pay for a more expensive path. Try the U trap with greedy search. In the open room, compare both tie-breakers. And under ‘relative to C∗C^*’, see which cells A* certainly expands.

Three things the figure teaches and the rest of the lesson proves:

  1. Cells with small ff are expanded first, and contours are level surfaces of ff. With w=0w = 0, f=gf = g and the contours are balls in the grid metric. With w=1w = 1, the expanded region consists of those with g∗(n)+h(n)g^*(n) + h(n) below optimal cost, hugging the path more tightly the better hh is.
  2. With w≤1w \le 1 the cost is always optimal and with w>1w > 1 it may not be, although it never exceeds ww times the optimum. This is weighted A* (Pohl, 1970), which you will study next lesson as bounded suboptimal search.
  3. Tie-breaking matters. In the open room there are many optimal paths and all their cells have the same ff. For equal ff, if the larger gg (farthest advanced) is preferred, A* goes straight; if the smaller gg 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. heapq does not permit decreasing an element’s priority, so when g[n′]g[n'] 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 gg, 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 ff, preferring the larger gg (equivalently, the smaller hh) advances in depth across the f=C∗f = C^* plateau and is the usual rule.

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 hh makes A* admissible.

Proof

Fix an optimal path π=(n0,n1,…,nk)\pi = (n_0, n_1, \dots, n_k) from start n0n_0 to goal nkn_k, costing C∗C^*.

Invariant. While A* has not terminated, the frontier contains a node nin_i on π\pi with g(ni)=g∗(ni)g(n_i) = g^*(n_i), the cost from π\pi to it. We prove this by induction on the number of expansions. Initially the frontier is {n0}\{n_0\} and g(n0)=0g(n_0) = 0. If a node other than that nin_i is expanded, nin_i remains in the frontier. If nin_i is expanded and is not the goal, ni+1n_{i+1} is generated with g=g∗(ni)+c(ni,ni+1)=g∗(ni+1)g = g^*(n_i) + c(n_i, n_{i+1}) = g^*(n_{i+1}) 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 G2G_2 with g(G2)>C∗g(G_2) > C^* is removed. Since h(G2)=0h(G_2) = 0, f(G2)=g(G2)>C∗f(G_2) = g(G_2) > C^*. But at that moment the frontier contains the invariant’s nin_i, with

f(ni)=g∗(ni)+h(ni)≤g∗(ni)+h∗(ni)=C∗,f(n_i) = g^*(n_i) + h(n_i) \le g^*(n_i) + h^*(n_i) = C^*,

where the inequality is admissibility and the final equality follows because nin_i lies on an optimal path. Thus f(ni)<f(G2)f(n_i) < f(G_2) and A* would have removed nin_i first. Contradiction.

Termination. Every node removed before the optimal goal has f≤C∗f \le C^* by the same argument, hence g≤C∗g \le C^*. With costs of at least ε\varepsilon, these nodes are paths of at most C∗/εC^*/\varepsilon actions, and finite branching makes their number finite. While no goal is removed, eventually the invariant’s nin_i is expanded and index ii advances; after finitely many steps a goal is removed, which by the preceding argument is optimal.

∎

The assumptions matter. Without ε>0\varepsilon > 0 there can be infinitely many bounded-cost paths (a chain with costs 2−k2^{-k}) and A* does not terminate. With inadmissible hh the argument fails at inequality f(ni)≤C∗f(n_i) \le C^*, and indeed a single node on an optimal path with hh too large is enough for A* to remove a worse goal first.

Graph search stores each state only once, breaking the previous invariant: if state nin_i on an optimal path was closed earlier with a worse gg, the better route to it never re-enters the frontier. A stronger, local condition is needed.

This is a triangle inequality: the estimate from nn 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 f=g+hf = g + h do not decrease, because a step increases gg by c(n,n′)c(n, n') and decreases hh by at most that amount. The converse is false: in the next figure’s graph, h(A)=4h(A) = 4, h(C)=0h(C) = 0 and c(A,C)=1c(A, C) = 1 is admissible (h∗(A)=4h^*(A) = 4) 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

ch(n,n′)=c(n,n′)−h(n)+h(n′).c_h(n, n') = c(n, n') - h(n) + h(n').

Consistency is exactly ch≥0c_h \ge 0. Along a path from start ss to nn, the hh terms cancel in a chain (telescoping sum), and

ch(camino)=c(camino)−h(s)+h(n).c_h(\text{camino}) = c(\text{camino}) - h(s) + h(n).

For fixed nn, term −h(s)+h(n)-h(s) + h(n) is the same for all paths, so shortest paths under cc and chc_h coincide. And reduced distance to node nn is g(n)+h(n)−h(s)=f(n)−h(s)g(n) + h(n) - h(s) = f(n) - h(s): Dijkstra on chc_h removes nodes in exactly the order ff, 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, h=h∗h = h^*, 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 γΦ(s′)−Φ(s)\gamma\Phi(s') - \Phi(s) 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 hh is admissible but inconsistent? In a tree nothing bad happens, by the first theorem. In a graph, a node may be removed with an gg worse than optimal, because the node leading to it along the good path has such a large hh that it waits in the frontier. If the good path appears later, the node is already closed.

InteractiveBreak consistency
131325Sh=3g=0 f=3Ah=4g=1 f=5Bh=3g=2 f=5Ch=0g=3 f=3Gh=0g=6 f=6
Pop goal G with g=6g = 6: finished. The optimum was 5: suboptimal solution.
step 5 of 5
  • closed (expanded)
  • on frontier
  • edge violating h(n)≤c(n,n′)+h(n′)h(n) \le c(n,n') + h(n')
  • returned path
Node to edit
4
Admissible (h≤h∗h \le h^*)yes
Consistentno (1 edge)
Returned / optimal cost6 / 5
Expansions (distinct nodes)4 (4)
Reopenings0
Admissible but inconsistent, without reopening: A* returns cost 6 and the optimum is 5. Enable reopening.
Each node displays its hh; the slider changes that of the selected node and its label shows the exact h∗h^*. Red edges violate h(n)≤c(n,n′)+h(n′)h(n) \le c(n,n') + h(n') in at least one direction. The player runs graph-search A* step by step (goal test on removal, tie-breaking by larger gg) with each node's gg and ff. With the initial heuristic, admissible but inconsistent on the edge between A and C, C closes with g=3g = 3 before A discovers the cost-2 path, and search returns 6 instead of 5. Enable reopening. Then lower h(A)h(A) until red disappears. The exponential family shows the price of reopening.

With the initial heuristic, h(S)=3h(S) = 3, h(A)=4h(A) = 4, h(B)=3h(B) = 3 and h(C)=h(G)=0h(C) = h(G) = 0. A* expands SS and the frontier contains CC (f=3+0f = 3 + 0), AA (f=1+4f = 1 + 4) and BB (f=2+3f = 2 + 3). It removes CC with g=3g = 3, closes it and generates GG with f=6f = 6. Then, from AA and BB, with f=5f = 5, it removes BB first (greater gg) and then AA, which discovers path S,A,CS, A, C of cost 2. But CC is closed. Without reopening, the next removal is GG with g=6g = 6. With reopening, CC returns to the frontier with g=2g = 2, f=2f = 2, and the goal leaves with g=5g = 5.

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 n′n' from nn, max⁡{h(n′),  h(n)−c(n,n′)}\max\{h(n'),\; h(n) - c(n, n')\} (Mérő, 1984, proposed it along with a second rule propagating values to the parent), and makes ff nondecreasing along the path by which each node is generated. But it does not make the heuristic consistent: in the figure, when AA generates CC, pathmax gives it h(C)=4−1=3h(C) = 4 - 1 = 3, and CC was already closed with g=3g = 3; 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 f∗(n)=g∗(n)+h(n)f^*(n) = g^*(n) + h(n) be the ff value with which nn would be removed if reached by its best path.

Proof

By the previous theorem, A* removes nodes in nondecreasing order of ff, each with g=g∗g = g^* and thus f=f∗f = f^*, and the optimal goal leaves with f=C∗f = C^*.

(1) Let nn have f∗(n)<C∗f^*(n) < C^* and let (s=m0,…,mj=n)(s = m_0, \dots, m_j = n) be an optimal path to it. By monotonicity of ff along paths, every mim_i satisfies f∗(mi)≤f∗(n)<C∗f^*(m_i) \le f^*(n) < C^*. While nn has not been expanded, the frontier contains the first unclosed mim_i with g=g∗(mi)g = g^*(m_i) (its predecessor is closed with its optimal gg), that is, with f<C∗f < C^*. Since the goal is removed with f=C∗f = C^*, all those mim_i are removed first, in particular nn.

(2) If f∗(n)>C∗f^*(n) > C^*, any entry for nn in the frontier has f≥f∗(n)>C∗f \ge f^*(n) > C^*, while until the end the frontier contains a node on an optimal path to the goal with f≤C∗f \le C^*. The goal leaves before nn.

∎

Thus A* with a consistent heuristic expands the entire {n:g∗(n)+h(n)<C∗}\{n : g^*(n) + h(n) < C^*\} “ball,” part of its boundary and nothing outside. This is what the first figure’s “relative to C∗C^*” mode shows: with w=1w = 1, 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 gg, 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 hh is admissible and access the problem only by expanding nodes and querying hh.

The first part uses an adversarial argument. Suppose an algorithm BB in the class terminates without expanding a node nn with f∗(n)<C∗f^*(n) < C^*. Construct an identical instance except that nn has a new successor, a goal G′G', with c(n,G′)=h(n)c(n, G') = h(n) and h(G′)=0h(G') = 0. The heuristic remains consistent (the new edge satisfies h(n)≤h(n)+0h(n) \le h(n) + 0), and the new optimal solution costs g∗(n)+h(n)=f∗(n)<C∗g^*(n) + h(n) = f^*(n) < C^*. Since BB never expanded nn, it cannot distinguish the two instances: it does the same on both and returns a solution costing C∗C^* on the second, which is no longer optimal. This contradicts BB being in the class.

The final qualification matters: this optimality concerns expansions with f∗<C∗f^* < C^*. Those on the f∗=C∗f^* = C^* 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 hR(n)≤h∗(n)h_R(n) \le h^*(n). And hRh_R is a graph distance: if n→n′n \to n' is an original action, it is also a relaxed action, and the triangle inequality for distances gives hR(n)≤c(n,n′)+hR(n′)h_R(n) \le c(n, n') + h_R(n').

∎

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.
InteractiveThe 8-puzzle relaxation ladder
5282122261314272
goal: 1 2 3 / 4 5 6 / 7 8 and blank
incomparableOriginal problemh*: computing it solves the puzzleLinear conflictsManhattan + conflictsGaschnigwithout “adjacent”Manhattanwithout “empty”Misplaced tileswithout both rulesh = 0uniform cost
each line connects a heuristic to one it dominates (checked over 181 440 states)
Sum of each tile's row and column distances to its goal: h=2+2+2+2+1+1+2+2=14h = 2 + 2 + 2 + 2 + 1 + 1 + 2 + 2 = 14.
Nodes expanded by A* (mean of 10 instances per depth, logarithmic scale)
  • h = 0
  • Misplaced tiles
  • Gaschnig
  • Manhattan
  • Linear conflicts
  • h* (model: d nodes)
no. 61, h* = 18
HeuristicManhattan
hh for this instance / h∗h^*14 / 18
Mean h/h∗h/h^* across 181 440 states0.642
Mean expanded at d=12d = 12 (b∗b^*)22.3 (1.092)
Mean expanded at d=24d = 24 (b∗b^*)818 (1.234)
Manhattan > Gaschnig in 177 591 of 181 440 states, and vice versa in 304: neither dominates the other. Their maximum dominates both.
Enable or disable the two movement rules, or click a diagram node: you get the corresponding relaxed-problem heuristic, broken down on one of 100 instances. Linear conflicts improve Manhattan but are not a relaxation of this kind (explained below). Each diagram line connects a heuristic with another it dominates, checked across all 181 440 states. The graph shows nodes expanded with each heuristic, averaged over 10 instances per optimal depth: data come from lesson cell code, which in the browser reproduces rows up to d=18d = 18 (uniform-cost up to d=10d = 10) and up to d=24d = 24 for Manhattan and conflicts; the rest was generated with the same code outside the browser. The h∗h^* series is not a measurement: with h=h∗h = h^* and tie-breaking by larger gg, search expands exactly the dd nodes of an optimal path.

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 33 and 11 in the top row with 33 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 n×nn \times n 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 hih_i are those with g∗(n)+hi(n)<C∗g^*(n) + h_i(n) < C^*. If g∗(n)+h2(n)<C∗g^*(n) + h_2(n) < C^*, then g∗(n)+h1(n)≤g∗(n)+h2(n)<C∗g^*(n) + h_1(n) \le g^*(n) + h_2(n) < C^*.

∎

This is a guarantee about sets, not times: the f∗=C∗f^* = C^* 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 h1,…,hmh_1, \dots, h_m are admissible, max⁡ihi\max_i h_i is admissible (each term is) and dominates all of them; if all are consistent, their maximum is too, because hi(n)≤c(n,n′)+hi(n′)≤c(n,n′)+max⁡jhj(n′)h_i(n) \le c(n, n') + h_i(n') \le c(n, n') + \max_j h_j(n') for each ii. In the 8-puzzle, max⁡(Manhattan,Gaschnig)\max(\text{Manhattan}, \text{Gaschnig}) exceeds Manhattan in those 304 states. Adding, by contrast, is valid only when heuristics count disjoint costs: if h1h_1 and h2h_2 measure the same thing, h1+h2h_1 + h_2 can reach 2h∗2h^*. 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 b∗≥0b^* \ge 0 and equals 11 at b∗=0b^* = 0, so for N≥1N \ge 1 there is a unique positive root, computed by bisection. With N=dN = d (a perfect heuristic with good tie-breaking, expanding only the dd nodes on the path) it gives b∗=1b^* = 1; 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 b∗b^*. For d=18d = 18, misplaced tiles give b∗=1.369b^* = 1.369, Gaschnig 1.3411.341, Manhattan 1.2221.222 and linear conflicts 1.1711.171. The order respects dominance, and the difference grows with depth: at d=18d = 18, Manhattan expands 197.4 nodes on average and misplaced tiles 1060.1.

b∗b^* is not a perfect constant either. In the data it grows with dd at small depths and stabilizes: Manhattan gives 1.2221.222, 1.2241.224, 1.2341.234 and 1.2341.234 for d=18d = 18, 2020, 2222 and 2424.

Relative error

What determines b∗b^*? Classic analysis (Pearl, 1984; Russell and Norvig summarize it in chapter 3) measures the quality of hh by its error. With constant relative error ε=(h∗−h)/h∗\varepsilon = (h^* - h)/h^*, in a space with one goal and reversible actions, expanded nodes grow as bεdb^{\varepsilon d}, where bb is the space’s branching factor: A* behaves like blind search whose effective depth is only the fraction ε\varepsilon of the path the heuristic cannot see. In terms of b∗b^*, this is b∗≈bεb^* \approx b^{\varepsilon}. The consequence is harsh: unless error grows at most logarithmically with h∗h^*, 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 ε\varepsilon on the initial states and the implied bb, (b∗)1/ε(b^*)^{1/\varepsilon}. For Manhattan and linear conflicts, between d=14d = 14 and d=24d = 24, the implied bb 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 GkG_k with k+1k + 1 nodes where A* needs O(2k)\bigO(2^k) expansions, and proposed a variant, algorithm B, with worst case O(N2)\bigO(N^2) (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 nkn_k (start), nk−1,…,n0n_{k-1}, \dots, n_0 (goal), with an edge ni→njn_i \to n_j for every i>ji > j. Skipping node nln_l costs 2l2^l extra, so the unique optimal path visits them all in order; and every intermediate njn_j has h(nj)=2j+2+jh(n_j) = 2^{j+2} + j, admissible but so large relative to lower-index nodes that njn_{j} is not expanded until everything below it has been explored with a worse gg. When it is finally expanded, it improves gg for all lower nodes, which reopen and are explored again in the same pattern. The removal order for k=4k = 4 is n4,n1,n2,n1,n3,n1,n2,n1,n0n_4, n_1, n_2, n_1, n_3, n_1, n_2, n_1, n_0: the “ruler” sequence of a binary counter. Expansions number exactly 2k−12^{k-1} for kk distinct nodes expanded: for k=12k = 12, 2048 expansions and 2036 reopenings. Without reopening, search performs only kk expansions but returns a suboptimal path.

The exponential worst case requires edge weights and hh 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 δ\delta, so each reopening lowers the node’s gg by at least δ\delta; many reopenings of one node require some hh to be enormous. Thus if weights are bounded by a constant independent of graph size, A* with an inconsistent heuristic performs at most O(N2)\bigO(N^2) 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 n1n_1 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 gg and, if tied, arrival order.

[ ]A* from scratch, with optional reopeningBrowser
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 S,C,GS, C, G; with it, cost 5 via S,A,C,GS, A, C, G and one reopening. The shortcut shows the first common mistake: the direct edge S→GS \to G costing 10 generates the goal in the first step, but the path through AA 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 h∗h^* for all states by breadth-first search from the goal (moves are reversible, so distance from the goal is distance to it).

[ ]The 8-puzzle, its heuristics and exact h*Browser
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.

[ ]Dominance over the entire state spaceBrowser
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 h(s)≤1+h(t)h(s) \le 1 + h(t) 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 b∗b^*

Instances are chosen randomly, 10 per optimal depth d=6,8,…,24d = 6, 8, \dots, 24, among states that BFS places at that distance. Uniform-cost (h=0h = 0) runs only up to d=10d = 10 to avoid taking too long.

[ ]Expanded nodes and effective branching factorBrowser
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)
[ ]Deeper: b* and relative errorBrowser
# 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 d=10d = 10, uniform-cost expands 597.2 nodes (b∗=1.740b^* = 1.740) and Manhattan 14.5 (b∗=1.067b^* = 1.067): a factor of 41. In the second, at d=24d = 24, 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 d=24d = 24 with the same data.

Greedy search and time

[ ]Greedy versus A*, and nodes versus secondsBrowser
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 d=24d = 24), and its node cost plateaus around 330 from d=18d = 18 onward, while A* keeps growing: it overtakes greedy at d=22d = 22 and is 2.5 times greater at d=24d = 24. 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

[ ]Exponential re-expansions with an inconsistent heuristicBrowser
# 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 kk expansions but returns, for k=12k = 12, 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 hh 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.

[ ]A* on a random geometric graph with networkxBrowser
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 hh gives generated nodes: 1196. A*‘s gain here is modest because nodes with g∗+h<C∗g^* + h < C^* occupy an ellipse-like region with foci at the two corners, which covers much of the square between opposite corners. The closer C∗C^* is to straight-line distance, that is, the straighter the graph’s paths, the narrower the region.

Common mistakes

Exercises

ProofConsistency implies admissibility, and f does not decrease
Prove: Let hh be consistent with h(G)=0h(G) = 0 at every goal GG. Then hh is admissible and, along any path n0,n1,…,nmn_0, n_1, \dots, n_m, the values f(ni)=g(ni)+h(ni)f(n_i) = g(n_i) + h(n_i), where g(ni)g(n_i) is the path cost to nin_i, do not decrease.
0
Start with admissibility: show that h(n)≤h∗(n)h(n) \le h^*(n) for every nn. If no goal is reachable from nn, h∗(n)=+∞h^*(n) = +\infty and there is nothing to prove.

Step 1 of 4. What do you induct on?

ProofGraph A* with a consistent heuristic is optimal
Prove: Let hh be consistent and costs positive. Graph-search A without reopening closes each node $n$ with $g(n) = g^(n),andthefirstgoalremovedhas, and the first goal removed has g = C^*$.
0
First prove that the ff values of removed nodes form a nondecreasing sequence; then, by induction over removal order, that each removed node has optimal gg. Do not use the text’s reduction to Dijkstra.

Step 1 of 4. Let nn be the node removed at one step, with value f(n)f(n). Why does the next removed node have f≥f(n)f \ge f(n)?

NumericThe effective branching factor
A finds a solution of depth $d = 5$ while expanding $N = 52$ nodes. Calculate the effective branching factor $b^,thepositiverootof, the positive root of 53 = 1 + b^ + (b^)^2 + (b^)^3 + (b^)^4 + (b^*)^5$, to three significant figures.
NumericGaschnig by hand
Calculate the Gaschnig heuristic for the 8-puzzle state with rows (1,2,3)(1, 2, 3), (5,4,_)(5, 4, \_), (8,7,6)(8, 7, 6), where _\_ is the blank and the goal is (1,2,3)(1, 2, 3), (4,5,6)(4, 5, 6), (7,8,_)(7, 8, \_).
QuizCombining heuristics
Let h1h_1 and h2h_2 be admissible. Which statements are true in general?

More than one answer may be correct.

QuizWhat does A* certainly expand?
With a consistent heuristic, optimal cost is C∗=10C^* = 10. Five nodes have these values of g∗g^* (optimal cost from the start) and hh: A with (3,5)(3, 5), B with (4,7)(4, 7), C with (6,4)(6, 4), D with (2,9)(2, 9) and E with (7,2)(7, 2). Which does A* expand regardless of tie-breaking?

More than one answer may be correct.

QuizGreedy search in trees and graphs
Greedy best-first search (f=hf = h) with an admissible heuristic in a finite state space with positive costs. What is true?
CodeLinear conflicts on an n × n board
Implement conflictos_lineales(estado, n) for the n×nn \times n sliding puzzle: estado is a tuple of length n2n^2 containing tiles by row and 0 for the blank, and the goal is (1,2,…,n2−1,0)(1, 2, \dots, n^2 - 1, 0). 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 n=4n = 4, 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 h
Shift+Enter to run

Summary

Key idea
A* orders the frontier by f=g+hf = g + h: cost paid plus an optimistic estimate of what remains. If the estimate never overestimates, the result is optimal; if it also satisfies the triangle inequality, A* is Dijkstra with reduced costs, never reopens a node and expands exactly what any algorithm with the same information would have to expand.
  • Greedy search (f=hf = h) is fast on deep problems but is not optimal, and in a tree is not even complete. Dijkstra (f=gf = g) is optimal but blind. A* (f=g+hf = g + h) lies between them, and f=g+w hf = g + w\,h spans the family.
  • Admissibility (h≤h∗h \le h^*) suffices for tree-search optimality. Graph search requires consistency (h(n)≤c(n,n′)+h(n′)h(n) \le c(n, n') + h(n')), which implies admissibility and monotonicity of ff, or reopening nodes.
  • A* with a consistent heuristic expands all nodes with g∗+h<C∗g^* + h < C^*, none with g∗+h>C∗g^* + h > C^*, and part of the =C∗= C^* 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 b∗b^*, which with relative error ε\varepsilon behaves like bεb^{\varepsilon}: 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.