Sam Austinon November 27, 202617 min read

Designing Heuristics for A*: Admissible and Consistent Heuristics Explained

Designing Heuristics for A*: Admissible and Consistent Heuristics Explained
Contents

Figure 1: Designing Heuristics for A: Admissible and Consistent Heuristics Explained — every route on the map is a search problem, and the quality of your estimate decides how much of it A* has to explore*

A* has a reputation for always finding the shortest path. That is only half true. A* finds the shortest path when your heuristic follows certain rules, and how fast it finds it depends entirely on how good that heuristic is. I will explain what "admissible" and "consistent" really mean, show what breaks when you violate them, and walk through how to design heuristics. I ran every number in this article in Python, so you can reproduce them.

A* in 60 Seconds

A* ranks each candidate node by f(n) = g(n) + h(n):

  • g(n): the exact cost of the path from the start to n.
  • h(n): your estimate of the cost from n to the goal.

A* always expands the node with the lowest f. Set h = 0 and you get Dijkstra's algorithm (uniform-cost search), which explores blindly in all directions. Rank by h alone (f = h) and you get greedy best-first search, which runs fast and can return poor paths. A* with a good heuristic sits between the two.

Admissible: Never Overestimate

A heuristic is admissible if it never overestimates the true remaining cost: h(n) ≤ h*(n) for every node, where h*(n) is the real cheapest cost to the goal. Admissible heuristics are optimistic, and optimism is what guarantees A* finds an optimal solution when costs are positive.

Why does that work? Here is the intuition behind the proof. Suppose A* is about to pick a suboptimal goal with cost C > C*. Somewhere on the true optimal path, a node n still sits on the frontier. Its f(n) = g(n) + h(n) ≤ g(n) + h*(n) = C*, which is less than C. So A* would pick n first. The optimal path always gets its turn before a worse goal can finish.

Classic admissible examples:

  • Straight-line (Euclidean) distance on a map, since roads can only add distance.
  • Manhattan distance on a 4-connected grid, since you cannot move diagonally.
  • Misplaced tiles and Manhattan distance in the 8-puzzle.

One caution: if the robot may move diagonally, Manhattan distance can overestimate the distance to the goal, so it stops being admissible. You will see the exact cost of that mistake below.

Consistent: A Triangle Inequality

A stronger property is consistency (also called monotonicity). A heuristic is consistent if, for every node n and every successor n' reached by an action with cost c(n, n'):

h(n) ≤ c(n, n') + h(n')

In plain words: the heuristic never drops by more than the actual edge cost as you take a step. That makes f non-decreasing along any path, so A* expands nodes in order of increasing f.

Two facts connect the properties:

  1. A consistent heuristic with h(goal) = 0 is automatically admissible.
  2. An admissible heuristic is not always consistent.

And the payoff of consistency is practical: when A* uses a consistent heuristic, the first time it expands any node, it has already found the optimal path to that node. No node ever needs a second look.

Why Consistency Matters: A Concrete Failure

With an inconsistent heuristic, A* may expand a node via an expensive path and later discover a cheaper one. If your implementation keeps a closed set and refuses to revisit closed nodes, it silently returns a wrong answer. I built a four-node graph to prove it. This code is runnable, and it prints both results:

import heapq

GRAPH = {"S": [("A", 1), ("B", 3)], "A": [("B", 1), ("G", 20)], "B": [("G", 5)], "G": []}
H = {"S": 0, "A": 6, "B": 0, "G": 0}

def astar(graph, h, start="S", goal="G", reopen=False):
    frontier, g, parent, closed = [(h[start], 0, start)], {start: 0}, {start: None}, set()
    while frontier:
        f, cost, node = heapq.heappop(frontier)
        if node in closed and not reopen:
            continue                      # closed set without reopening
        if node == goal:
            path, n = [], node
            while n:
                path.append(n); n = parent[n]
            return cost, path[::-1]
        closed.add(node)
        for nxt, w in graph[node]:
            new_cost = cost + w
            if new_cost < g.get(nxt, float("inf")):
                g[nxt], parent[nxt] = new_cost, node
                heapq.heappush(frontier, (new_cost + h[nxt], new_cost, nxt))

for reopen in (False, True):
    print(f"reopen={reopen}: {astar(GRAPH, H, reopen=reopen)}")

# reopen=False: (8, ['S', 'B', 'G'])
# reopen=True:  (7, ['S', 'A', 'B', 'G'])

The true optimum is S→A→B→G with cost 7. The heuristic is admissible (h*(A) = 6, h*(B) = 5, and every h value sits at or below these). But it is inconsistent, because h(A) = 6 > c(A,B) + h(B) = 1.

The closed-set version returns a suboptimal path, because it expands B early via the direct edge (cost 3) and never reconsiders it. The reopening version re-inserts B when it finds the cheaper path through A. If your heuristic is not consistent, use an explored dictionary instead of an explored set. FYI, many real heuristics are consistent in practice, but you should verify instead of assuming.

What Happens When You Overestimate?

Violating admissibility trades optimality for speed. I tested this on a 40×40 grid with random walls (about 22% blocked), 4-connected movement, and unit cost:

Heuristic Cost Nodes expanded
Zero (Dijkstra) 78 1,238
Chebyshev 78 1,080
Euclidean 78 1,065
Manhattan 78 898
2 × Manhattan (inadmissible) 84 94

Doubling Manhattan distance cut the expansions from 898 to 94, roughly a tenfold saving, and the path cost rose from 78 to 84. That is the idea behind weighted A*: inflate h by a factor, search much faster, and accept a bounded loss in path quality. With weight w, the returned cost is at most w times optimal when h is admissible, so verify that bound against a reference before you rely on it.

A subtler version of the same mistake appears when the problem changes under your heuristic. I allowed diagonal "king" moves at cost 1 and kept using Manhattan distance:

Heuristic Cost Nodes expanded
Chebyshev (exact in open space) 43 178
Manhattan (inadmissible here) 45 45

Manhattan now overestimates, so A* returned a path of cost 45 instead of 43. If you change the movement rules, recheck your heuristic.

Heuristic Quality: Dominance

If two heuristics are both admissible, the one with larger values dominates, and A* with the dominating heuristic expands fewer nodes. The rule of thumb is simple: make h(n) as large as possible, subject to h(n) ≤ h*(n).

The 8-puzzle shows it clearly. I ran 40 random scrambles (average optimal solution length 19.6 moves) with three heuristics, and every one returned the same optimal cost:

Heuristic Average nodes expanded
Zero 51,566
Misplaced tiles 5,271
Manhattan 653

Manhattan distance expands about eight times fewer nodes than misplaced tiles, which expands about ten times fewer than no heuristic at all. This matches the classic textbook comparison, where A* with Manhattan distance beat A* with misplaced tiles at every solution depth (at depth 8, 25 versus 39 nodes, against 6,384 for iterative deepening). Both heuristics are admissible, and Manhattan distance is always at least as large as misplaced tiles, so it dominates.

Four Reliable Ways to Design Heuristics

1. Relax the Problem

The most dependable method: remove some rules from the problem, then solve the easier problem exactly. Its optimal cost becomes your heuristic. For the 8-puzzle:

  1. Relax "tiles move only into the blank square" to "a tile can move anywhere," and the exact cost is the number of misplaced tiles.
  2. Relax it to "a tile can move to any adjacent square, even if occupied," and the exact cost is the sum of Manhattan distances.

Relaxed-problem costs are admissible because the relaxed problem has at least as many options as the real one. An exact relaxed cost is also consistent, since it satisfies the triangle inequality in the relaxed problem.

2. Pattern Databases

Precompute exact costs for a subproblem, such as getting tiles 1 through 4 into place while ignoring the others, and store them in a table. During search, look up the current pattern. The approach is standard: precompute and save the exact solution cost for every possible subproblem instance. You pay memory and preprocessing time and gain much stronger estimates.

3. Combine With a Maximum

If h1 and h2 are both admissible, then max(h1, h2) is admissible and at least as informed as either. The maximum of consistent heuristics also stays consistent. This makes it easy to mix cheap and expensive estimates without breaking the guarantee.

4. Learn or Precompute Landmarks

On road networks, practitioners precompute distances to a few landmark nodes and use the triangle inequality to bound distances. The classic ALT method (A*, landmarks, triangle inequality) is the one to read first. Learned heuristics, such as neural network estimates, can speed up search a lot, but they carry no admissibility guarantee, so treat the output as inadmissible unless you have proven otherwise.

Test Your Heuristic in Code

Do not trust a hand proof alone. Run a consistency check over sampled edges:

def is_consistent(h, neighbors, states):
    violations = 0
    for s in states:
        for t, c in neighbors(s):
            if h(s) > c + h(t):
                violations += 1
    return violations

I ran this on every state reachable from two 8-puzzle scrambles, 32,742 states in all, and found zero violations for both misplaced tiles and Manhattan distance. A check like this samples states, so it can disprove consistency but cannot prove it for the whole state space.

To test admissibility, compute true costs with a reverse Dijkstra search from the goal on a small instance, then confirm h(s) ≤ h*(s) for every state. I have not run that exact snippet here, but it is the standard approach. Also compare A* results against Dijkstra on random problems: if a path ever costs more than Dijkstra's answer, your heuristic overestimates somewhere.

Practical Tips

  • Weigh the cost of computing h. An expensive heuristic can lose to a cheap, weaker one if each call dominates your runtime.
  • Break ties thoughtfully. Among equal f values, prefer larger g (deeper nodes); it often reduces expansions.
  • Use consistent heuristics when you can. They allow simpler code and faster searches, since no reopening happens.
  • Match the heuristic to the movement rules. Revalidate after any change to costs or moves.
  • Keep integer costs where possible. Floating-point comparisons add subtle bugs.

Common Pitfalls

  • Using Euclidean distance with costs that are not distances. Unit-cost grids and weighted terrain break the units.
  • Overestimating without realizing it. Check every rule change, like diagonal moves.
  • Closed set plus inconsistent heuristic. You may return suboptimal paths, as the four-node example showed.
  • Assuming a bigger heuristic is always better. It must stay at or below the true cost.
  • Skipping tests against Dijkstra. Bugs hide in the cases you did not think about.
  • Believing A* guarantees speed. The guarantee covers optimality, not runtime.
  • Forgetting h(goal) = 0. Consistency alone only implies admissibility when the goal's estimate is zero.

Best Book to Read

CoverBookDescriptionGet it
Cover of “Heuristics: Intelligent Search Strategies for Computer Problem Solving” Heuristics: Intelligent Search Strategies for Computer Problem Solvingby Judea Pearl the classic monograph on best-first search, admissibility, and heuristic power, and still the deepest treatment of why A* works. View on Amazon

As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.

Read it after you have made the four-node bug above fail for yourself. Pearl's formal treatment of admissibility and monotonicity makes much more sense once you have watched a closed set return cost 8 on a graph whose optimum is 7.

Wrapping Up

Admissible means h never exceeds the true remaining cost, which guarantees optimal paths. Consistent means h obeys the triangle inequality across every edge, which also prevents reopening nodes and keeps f non-decreasing.

Make your heuristic as large as possible without breaking admissibility, design it by relaxing the problem, and test it against Dijkstra before you trust it. The same discipline applies when you swap A* for a learned policy: a stronger estimate is only useful if you know what it is allowed to claim. That is the thread running through the classical AI overview and the RL versus solver comparisons.

Pick a small search problem of your own, run it with h = 0, then add your best heuristic and compare the expansion counts. If the cost matches and the node count drops, you have built a good one. Which problem will you speed up first?

Frequently Asked Questions

What does it mean for an A* heuristic to be admissible?

A heuristic is admissible when it never overestimates the true cost to the goal: h(n) ≤ h*(n) for every node. Admissible heuristics are optimistic, and that optimism guarantees A* returns an optimal path when edge costs are positive.

What is the difference between an admissible and a consistent heuristic?

Admissibility concerns the goal only: h(n) ≤ h*(n). Consistency concerns every edge: h(n) ≤ c(n, n') + h(n') for each successor. A consistent heuristic with h(goal) = 0 is automatically admissible, but an admissible heuristic is not always consistent.

What happens if my A* heuristic overestimates?

You lose the optimality guarantee. A* can settle on a suboptimal goal before the optimal path reaches the front. The upside is speed: inflating the heuristic, as weighted A* does, expands far fewer nodes and returns a path whose cost is bounded relative to optimal.

How do I design an admissible heuristic?

Relax the problem by removing a rule, then solve the easier problem exactly and use its optimal cost as h. Other approaches include pattern databases that precompute exact costs for subproblems, taking the maximum of several admissible heuristics, and landmark-based bounds computed with the triangle inequality.

Does an admissible heuristic guarantee A* will be fast?

No. Admissibility guarantees optimality, not runtime. A weak admissible heuristic expands almost as many nodes as Dijkstra, while a stronger one that stays at or below the true cost expands far fewer. That is why heuristic quality, not just correctness, drives speed.

Sources

  • [1] Russell and Norvig, Artificial Intelligence: A Modern Approach (4th edition) — admissibility, consistency, dominance, weighted A*, and the 8-puzzle comparison: aima.cs.berkeley.edu
  • [2] Hart, Nilsson, and Raphael, A Formal Basis for the Heuristic Determination of Minimum Cost Paths (1968) — the original A* paper: doi.org
  • [3] Dechter and Pearl, Generalized Best-First Search Strategies and the Optimality of A* (1985) — the formal treatment of admissibility, monotonicity, and node reopening: doi.org
  • [4] Goldberg and Harrelson, Computing the Shortest Path: A* Search Meets Graph Theory (2005) — landmark-based ALT bounds on road networks: microsoft.com
  • [5] University of Oxford, AI Problem Solving with Search & Logic — the course outline covering search, optimisation, and planning: cs.ox.ac.uk

What are You Looking For?

esc