TExcelTAD
Home › Game AI › Heuristics

Heuristics

The heuristic h(n) is the only part of A* you design yourself, and it decides both how fast the search is and whether its answer is the cheapest path. This lesson compares the common heuristics on the same map and shows the two properties that matter: admissible and consistent.

The two properties

Property Definition What it buys you
Admissible h(n) never exceeds the true cheapest cost from n to the goal A* returns an optimal path
Consistent (monotone) h(n) ≤ cost(n, m) + h(m) for every edge n → m a node's g is final when it's first expanded, so the closed set never needs reopening

Consistent implies admissible. All the distance heuristics below are consistent for the movement they're designed for. The trap is using one designed for different movement: the Manhattan distance assumes you can't move diagonally, so on an 8-connected grid it overestimates diagonal routes.

The standard grid heuristics

With dx = |x − goal.x| and dy = |y − goal.y|:

Heuristic Formula Exact for
Zero 0 nothing; A* becomes Dijkstra
Manhattan dx + dy 4-connected grids
Chebyshev max(dx, dy) 8-connected, diagonal costs 1
Octile max(dx, dy) + (√2 − 1) · min(dx, dy) 8-connected, diagonal costs √2
Euclidean √(dx² + dy²) any-angle movement (navmeshes)

The closer h is to the true remaining cost without going over, the fewer nodes A* expands. On an 8-connected grid with √2 diagonals, octile is the tightest admissible choice; Euclidean is admissible but lower, so A* expands more.

Comparing them on one map

An 8-connected map (no corner cutting) with two walls between the start and the goal, which sits diagonally across the room. Each heuristic runs the same A*; the table prints the path cost, the number of expanded nodes, and whether the path is optimal:

csharp · try it yourself
using System;
using System.Collections.Generic;

string[] map =
{
    "######################",
    "#S...................#",
    "#.......#............#",
    "#.......#............#",
    "#.......#....#.......#",
    "#.......#....#.......#",
    "#............#.......#",
    "#............#.....G.#",
    "######################",
};
var start = (x: 1, y: 1);
var goal = (x: 19, y: 7);
double D2 = Math.Sqrt(2);

var heuristics = new (string name, Func<int, int, double> h)[]
{
    ("zero (Dijkstra)", (dx, dy) => 0),
    ("Euclidean",       (dx, dy) => Math.Sqrt(dx * dx + dy * dy)),
    ("octile",          (dx, dy) => Math.Max(dx, dy) + (D2 - 1) * Math.Min(dx, dy)),
    ("Manhattan",       (dx, dy) => dx + dy),
    ("2 x octile",      (dx, dy) => 2 * (Math.Max(dx, dy) + (D2 - 1) * Math.Min(dx, dy))),
};

double optimal = AStar(heuristics[0].h).cost;
Console.WriteLine("heuristic        cost    expanded  optimal?");
foreach (var (name, h) in heuristics)
{
    var (cost, expanded) = AStar(h);
    Console.WriteLine(
quot;{name,-15} {cost,6:F3} {expanded,9} {(Math.Abs(cost - optimal) < 1e-9 ? "yes" : "no")}"); } (double cost, int expanded) AStar(Func<int, int, double> hf) { double H((int x, int y) c) => hf(Math.Abs(c.x - goal.x), Math.Abs(c.y - goal.y)); bool Free(int x, int y) => map[y][x] != '#'; var g = new Dictionary<(int x, int y), double> { [start] = 0 }; var open = new PriorityQueue<(int x, int y), (double f, double h, int order)>(); var closed = new HashSet<(int x, int y)>(); int order = 0; open.Enqueue(start, (H(start), H(start), order++)); while (open.TryDequeue(out var cur, out _)) { if (!closed.Add(cur)) continue; if (cur == goal) return (g[cur], closed.Count); for (int dy = -1; dy <= 1; dy++) for (int dx = -1; dx <= 1; dx++) { if (dx == 0 && dy == 0) continue; var next = (x: cur.x + dx, y: cur.y + dy); if (!Free(next.x, next.y) || closed.Contains(next)) continue; if (dx != 0 && dy != 0 && (!Free(cur.x + dx, cur.y) || !Free(cur.x, cur.y + dy))) continue; // no corner cutting double newG = g[cur] + (dx != 0 && dy != 0 ? D2 : 1); if (g.TryGetValue(next, out double old) && old <= newG) continue; g[next] = newG; open.Enqueue(next, (newG + H(next), H(next), order++)); } } return (double.PositiveInfinity, closed.Count); }
heuristic        cost    expanded  optimal?
zero (Dijkstra) 20.485       129  yes
Euclidean       20.485        69  yes
octile          20.485        58  yes
Manhattan       20.485        71  yes
2 x octile      23.799        29  no

Read the table from the top. Zero, Euclidean and octile are all admissible, and the tighter the estimate, the fewer nodes: octile, which is exact on open ground, expands less than half of what Dijkstra does. Manhattan happened to find the optimal cost on this map, but nothing guaranteed it, and it expanded more nodes than octile: it overrates every diagonal, so it keeps preferring straight moves that don't actually bring it closer. The doubled octile is the fastest by far, and its path is about 16 % longer.

Weighted A*: trading optimality for speed

Multiplying an admissible heuristic by a weight w > 1 is called weighted A*. It's greedier: it trusts the estimate more than the cost so far. Its paths are guaranteed to cost at most w times the optimum, and in practice they're usually within a few percent while expanding a fraction of the nodes. Many games use a weight of 1.1–1.5 for long-range paths, because nobody notices a path 2 % longer but everybody notices a frame hitch. Push it to infinity and you get greedy best-first search, which ignores g completely: very fast, and happy to walk into long dead ends.

Tip: Exactness only matters where players can see it. A unit crossing the whole map can use a weighted heuristic; a guard chasing the player through a room should not.

Ties and the "staircase" problem

On open ground many paths have the same cost, so many nodes share the same f. Which one you expand first changes both speed and path shape:

  • Breaking ties towards the smaller h (as in this course) keeps the search diving towards the goal instead of widening on a plateau of equal f values.
  • Some games add a tiny bias, such as multiplying h by 1 + 1/1000, to get the same effect. It's technically inadmissible but changes costs by far less than one step.
  • Equal-cost paths can still look like staircases or hug walls. Fix the shape afterwards with Path Smoothing rather than fighting it in the heuristic.

Beyond distance

On a big map, a straight-line distance badly underestimates when the real route goes around a mountain range, and A* expands everything in front of it. Precomputed heuristics fix that: landmarks (ALT) store exact distances from a few chosen points and use the triangle inequality to get much tighter bounds, and hierarchical pathfinding (HPA*) searches a coarse graph of regions first. Both cost memory and a build step, so reach for them only after profiling shows searches are the bottleneck.

Test yourself

Why is the Manhattan distance a poor heuristic on an 8-connected grid?

  1. It is too small
  2. It overestimates diagonal routes, so it isn't admissible there and A* can return a non-optimal path
  3. It can't handle walls
  4. It's slower to compute

Which heuristic is exact on an open 8-connected grid where diagonals cost √2?

  1. Manhattan
  2. Euclidean
  3. Octile
  4. Zero

What does weighted A* with w = 1.5 guarantee?

  1. The optimal path
  2. A path costing at most 1.5 × the optimal cost (with an admissible base heuristic)
  3. Fewer than 1.5 nodes expanded
  4. Nothing