Sub topic 11
Comparing Heuristics: Dominance and Nodes Expanded
Earlier chapters showed that any admissible heuristic makes A* return an optimal path. That leaves a practical question. If two heuristics are both admissible, which one should you use? This chapter answers it with three tools: dominance, counting nodes expanded, and the effective branching factor.
It assumes you have read the earlier chapters on admissible and consistent heuristics and on grid heuristics. You should also be able to run Python and read the binary-heap A* implementation from earlier in the tutorial.
Why Larger Admissible Estimates Help
Recall what A expands when the heuristic is consistent. Let C be the cost of the optimal path. Then:
| Condition on a node n | What A* does with n |
|---|---|
| f(n) < C* | Always expanded |
| f(n) = C* | Maybe expanded, depending on tie-breaking |
| f(n) > C* | Never expanded |
Because f(n) = g(n) + h(n), the first row becomes h(n) < C − g(n). That inequality explains everything else in this chapter. If you raise h(n) while keeping it admissible, fewer nodes satisfy the inequality, so fewer nodes get expanded. The zero heuristic h(n) = 0 turns A into uniform-cost search, and it expands every node with g(n) < C. The perfect heuristic h(n), the true remaining cost, expands only nodes on optimal paths, plus whatever tie-breaking lets in.
Dominance
Take two admissible heuristics h1 and h2. h2 dominates h1 if h2(n) ≥ h1(n) for every node n.
When both heuristics are consistent and h2 dominates h1, every node that A with h2 must expand is also expanded by A with h1. The proof follows from the table above. If A with h2 surely expands n, then g(n) + h2(n) < C. Since h1(n) ≤ h2(n), it follows that g(n) + h1(n) < C too, so A with h1 expands n as well. Here g(n) is the optimal cost to n in both runs, because consistent heuristics close each node with its optimal g.
The grid heuristics from the previous chapter form a dominance chain on a 4-connected grid with unit costs. For any two cells, Euclidean distance is at most Manhattan distance, and both are at most the true path length.
Heuristics that cannot be compared
Dominance is a partial order. Two heuristics can each be larger on different nodes, and then neither dominates the other. For example, on an 8-puzzle, a heuristic that counts misplaced tiles in the top row only and another that counts them in the bottom row only are not comparable.
The fix is to take their maximum. If h1 and h2 are admissible, then h(n) = max(h1(n), h2(n)) is admissible, and it dominates both of them. If both are consistent, the maximum is consistent too.
def max_heuristic(*hs):
return lambda n: max(h(n) for h in hs)The catch is cost per node. The maximum evaluates every component heuristic at every generated node.
Measuring: Count Nodes Expanded
Dominance tells you which heuristic is at least as informed. Measuring tells you by how much. The following self-contained script instruments A* to count expansions. A node counts as expanded when it is popped from the heap and has not already been closed. It then runs three heuristics on a grid with a wall that forces a detour.
import heapq
import math
from itertools import count
def astar_count(start, goal, neighbors, h):
tie = count()
open_heap = [(h(start), next(tie), start)]
g = {start: 0}
parent = {start: None}
closed = set()
expanded = 0
while open_heap:
_, _, node = heapq.heappop(open_heap)
if node in closed:
continue
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal], expanded
closed.add(node)
expanded += 1
for nxt, cost in neighbors(node):
new_g = g[node] + cost
if new_g < g.get(nxt, float('inf')):
g[nxt] = new_g
parent[nxt] = node
heapq.heappush(open_heap, (new_g + h(nxt), next(tie), nxt))
return None, float('inf'), expanded
def grid_neighbors(grid):
rows, cols = len(grid), len(grid[0])
def neighbors(cell):
r, c = cell
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == '.':
yield (nr, nc), 1
return neighbors
def manhattan(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def euclidean(a, b):
return math.hypot(a[0] - b[0], a[1] - b[1])
rows, cols = 15, 15
grid = [['.'] * cols for _ in range(rows)]
for r in range(1, rows - 1):
grid[r][7] = '#' # wall with gaps at the top and bottom rows
start, goal = (7, 0), (7, 14)
nbrs = grid_neighbors(grid)
heuristics = {
"zero": lambda n: 0,
"euclidean": lambda n: euclidean(n, goal),
"manhattan": lambda n: manhattan(n, goal),
}
for name, h in heuristics.items():
path, cost, expanded = astar_count(start, goal, nbrs, h)
print(f"{name:10s} cost={cost} depth={len(path) - 1} expanded={expanded}")All three runs report the same cost, because all three heuristics are admissible. The expansion counts should fall from zero to Euclidean to Manhattan, which matches the dominance chain. Change the wall or the start and goal and run it again. The ordering of the forced sets stays fixed, though the gaps between the counts change with the map.
Effective Branching Factor
Raw counts depend on how deep the solution is, so comparing them across problems of different depths can mislead you. The effective branching factor b removes that dependence. If A expands N nodes to find a solution at depth d, then b* is the branching factor that a uniform tree of depth d would need to contain N + 1 nodes:
N + 1 = 1 + b + (b)² + … + (b*)^d
A perfect heuristic gives b close to 1. A weak heuristic gives b close to the problem's real branching factor. For example, if a search expands 52 nodes for a solution at depth 5, then b* ≈ 1.92. You can check this by computing 1 + 1.92 + 1.92² + 1.92³ + 1.92⁴ + 1.92⁵ ≈ 53.
There is no closed form for b*, but the sum grows monotonically in b, so bisection solves it:
def effective_branching_factor(n_expanded, depth, tol=1e-9):
if depth == 0:
return 0.0
target = n_expanded + 1
def total(b):
return sum(b ** i for i in range(depth + 1))
lo, hi = 0.0, max(1.0, float(n_expanded))
while hi - lo > tol:
mid = (lo + hi) / 2
if total(mid) < target:
lo = mid
else:
hi = mid
return (lo + hi) / 2
print(round(effective_branching_factor(52, 5), 2)) # 1.92A good heuristic keeps b roughly constant as problems get harder. That makes b useful for comparing heuristics on a sample of random instances: average it across instances of similar depth and compare the averages.
Gotchas When Comparing Heuristics
| Pitfall | Why it misleads | What to do |
|---|---|---|
| Comparing an inadmissible heuristic | A larger inadmissible h expands fewer nodes but can return worse paths | Compare only admissible heuristics, or check returned costs too |
| Ignoring per-node cost | A heuristic that halves expansions but costs 10× to compute is slower overall | Measure wall-clock time along with expansions |
| Testing one instance | Tie-breaking and map layout can flip counts on a single problem | Average over many random start and goal pairs |
| Ignoring ties at f = C* | On open grids many nodes share f = C*, so the counts depend on tie order | Fix the tie-breaking rule across runs (covered in the next chapter) |
| Admissible but inconsistent h | Nodes may be reopened, so the clean superset argument no longer applies | Prefer consistent heuristics, or count reopenings separately |
The decision rule is this: among admissible heuristics, prefer the dominating one unless its per-node cost outweighs the expansions it saves. When neither dominates, take the maximum and measure whether the extra evaluation pays for itself.
Exercise
On an 8-connected grid where diagonal moves cost sqrt(2), rank the zero heuristic, Euclidean, and octile distance by dominance. Which one should expand the fewest forced nodes?
Show answer
Zero ≤ Euclidean ≤ octile on every cell, and all three are admissible and consistent for this movement model. Octile dominates both of the others, so it expands the fewest nodes with f(n) < C*. Euclidean comes next, and the zero heuristic, which is uniform-cost search, expands the most.
Exercise
You have two admissible, consistent heuristics for a puzzle. h1 is larger on some states and h2 is larger on others. How can you get a heuristic at least as good as both, and what is the trade-off?
Show answer
Use h(n) = max(h1(n), h2(n)). It is admissible and consistent, and it dominates both, so its forced expansion set is no larger than either one's. The trade-off is that both heuristics are computed at every generated node, so the time per node goes up. Measure wall-clock time to check that the saved expansions outweigh that cost.
Exercise
A with heuristic hA expands 120 nodes on a depth-6 problem. With hB it expands 40 nodes on the same problem. Use effectivebranchingfactor to compute b for each, and explain what the values tell you.
Show answer
b is about 2.0 for hA and about 1.6 for hB (run the function to get the exact values). The lower b for hB means each level of the search grows by a smaller factor, so hB guides the search more tightly. The gap between the two heuristics will widen on deeper problems, because the node count grows roughly like b* raised to the depth.