TExcelTAD
Home › Game AI › A* Search

A* Search

Dijkstra's algorithm finds the cheapest path, but it searches in every direction equally, including straight away from the goal. A* (say "A-star") adds one piece of knowledge: an estimate of how far each node still is from the goal. It is the default pathfinder in games, and every engine's navigation system runs a variant of it.

f = g + h

For every node A* keeps:

Value Meaning
g(n) the real cost from the start to n along the best path found so far (what Dijkstra uses)
h(n) the heuristic: an estimate of the cost from n to the goal
f(n) = g(n) + h(n) the estimated cost of the cheapest full path through n

The priority queue (the open set) is ordered by f instead of g. Nodes that are cheap to reach and look close to the goal come out first, so the search runs towards the goal and only spreads sideways when something blocks it. Nodes already expanded form the closed set.

On a 4-connected grid the natural heuristic is the Manhattan distance |dx| + |dy|: you can never reach the goal in fewer steps than that, so it never overestimates. That property, being admissible, guarantees that A* still returns the cheapest path. Heuristics covers the other choices.

Watching A* think

A tiny map, with every expansion printed. When two nodes have the same f, the one with the smaller h (closer to the goal) wins, then the one inserted first:

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

string[] map =
{
    "#######",
    "#S.#.G#",
    "#..#..#",
    "#.....#",
    "#######",
};
var start = (x: 1, y: 1);
var goal = (x: 5, y: 1);
var dirs = new (int dx, int dy)[] { (0, -1), (1, 0), (0, 1), (-1, 0) };
int H((int x, int y) c) => Math.Abs(c.x - goal.x) + Math.Abs(c.y - goal.y);

var g = new Dictionary<(int x, int y), int> { [start] = 0 };
var cameFrom = new Dictionary<(int x, int y), (int x, int y)>();
var open = new PriorityQueue<(int x, int y), (int f, int 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 var pri))
{
    if (!closed.Add(cur)) continue;                       // already expanded via a cheaper entry
    Console.WriteLine(
quot;expand ({cur.x},{cur.y}) g={g[cur]} h={pri.h} f={pri.f}"); if (cur == goal) break; foreach (var (dx, dy) in dirs) { var next = (x: cur.x + dx, y: cur.y + dy); if (map[next.y][next.x] == '#' || closed.Contains(next)) continue; int newG = g[cur] + 1; if (g.TryGetValue(next, out int old) && old <= newG) continue; g[next] = newG; cameFrom[next] = cur; open.Enqueue(next, (newG + H(next), H(next), order++)); } } var path = new List<string>(); for (var c = goal; c != start; c = cameFrom[c]) path.Add(
quot;({c.x},{c.y})"); path.Add(
quot;({start.x},{start.y})"); path.Reverse(); Console.WriteLine(
quot;path cost {g[goal]}: {string.Join(" ", path)}");
expand (1,1)  g=0 h=4 f=4
expand (2,1)  g=1 h=3 f=4
expand (2,2)  g=2 h=4 f=6
expand (1,2)  g=1 h=5 f=6
expand (2,3)  g=3 h=5 f=8
expand (3,3)  g=4 h=4 f=8
expand (4,3)  g=5 h=3 f=8
expand (4,2)  g=6 h=2 f=8
expand (4,1)  g=7 h=1 f=8
expand (5,1)  g=8 h=0 f=8
path cost 8: (1,1) (2,1) (2,2) (2,3) (3,3) (4,3) (4,2) (4,1) (5,1)

The start's f is 4, the Manhattan distance to the goal, but the wall forces a detour: every step that goes away from the goal (down, then back up) raises f by 2. A* drains all the nodes with the lowest f before it accepts a more expensive one, so it tries everything at f = 4, then f = 6, and only then the real route at f = 8. That ordering is why, the first time it pops the goal, no cheaper path can exist.

Dijkstra vs A* on an open map

The classic demonstration: an open room with a cup-shaped wall facing the start. Both searches return a path of the same cost; the difference is how much of the map they expand (o marks expanded cells that aren't on the path):

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

string[] map =
{
    "####################",
    "#..................#",
    "#..................#",
    "#.......#####......#",
    "#S..........#....G.#",
    "#.......#####......#",
    "#..................#",
    "#..................#",
    "####################",
};
var start = (x: 1, y: 4);
var goal = (x: 17, y: 4);
var dirs = new (int dx, int dy)[] { (0, -1), (1, 0), (0, 1), (-1, 0) };

Run("Dijkstra (h = 0)", useHeuristic: false);
Run("A* (Manhattan)", useHeuristic: true);

void Run(string title, bool useHeuristic)
{
    int H((int x, int y) c) => useHeuristic ? Math.Abs(c.x - goal.x) + Math.Abs(c.y - goal.y) : 0;
    var g = new Dictionary<(int x, int y), int> { [start] = 0 };
    var cameFrom = new Dictionary<(int x, int y), (int x, int y)>();
    var open = new PriorityQueue<(int x, int y), (int f, int 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) break;
        foreach (var (dx, dy) in dirs)
        {
            var next = (x: cur.x + dx, y: cur.y + dy);
            if (map[next.y][next.x] == '#' || closed.Contains(next)) continue;
            int newG = g[cur] + 1;
            if (g.TryGetValue(next, out int old) && old <= newG) continue;
            g[next] = newG;
            cameFrom[next] = cur;
            open.Enqueue(next, (newG + H(next), H(next), order++));
        }
    }
    var grid = Array.ConvertAll(map, row => row.ToCharArray());
    foreach (var c in closed) if (c != start && c != goal) grid[c.y][c.x] = 'o';
    for (var c = cameFrom[goal]; c != start; c = cameFrom[c]) grid[c.y][c.x] = '*';
    Console.WriteLine(
quot;{title}: cost {g[goal]}, expanded {closed.Count}"); foreach (var row in grid) Console.WriteLine(" " + new string(row)); }
Dijkstra (h = 0): cost 20, expanded 112
  ####################
  #oooooooooooooooooo#
  #*****************o#
  #*oooooo#####oooo*o#
  #Soooooooooo#ooooG.#
  #ooooooo#####ooooo.#
  #oooooooooooooooooo#
  #ooooooooooooooooo.#
  ####################
A* (Manhattan): cost 20, expanded 38
  ####################
  #..................#
  #......***********.#
  #oooooo*#####....*.#
  #S******oooo#....G.#
  #ooooooo#####......#
  #..................#
  #..................#
  ####################

Same cost, a fraction of the work. A* only had to explore the inside of the cup (the heuristic said "the goal is right there, through the wall") before spilling around its edge. Dijkstra flooded the whole room. On a big level this is the difference between a search costing a millisecond and costing fifty.

Step through Dijkstra and A*

The same open room with a cup-shaped wall, stepped one expansion at a time. Labels show each cell's cost so far (Dijkstra) or f = g + h (A*); ~ cells are mud and cost 3 to enter. Compare how many cells each one expands before it reaches the goal:

Try it: A* on a clickable grid

Draw walls by clicking or dragging on the grid, choose Start or Goal and click to move them, then press Step to expand one node at a time or Play to animate. Light cells are the open set, darker cells the closed set, and the yellow line is the final path. Switch the search to Dijkstra to see the flood, or to a weighted A* to see a greedier search (see Heuristics).

html · try it yourself
<style>
  html, body { margin: 0; background: #10141c; color: #dde3ee; font: 13px system-ui, sans-serif; }
  .bar { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; padding: 6px 8px; }
  button, select { font: inherit; background: #222a38; color: #dde3ee; border: 1px solid #3a4558; border-radius: 4px; padding: 3px 9px; cursor: pointer; }
  button.on { background: #3d6bd8; border-color: #3d6bd8; }
  canvas { display: block; margin: 0 auto; max-width: 100%; height: auto; touch-action: none; cursor: crosshair; }
  #stats { padding: 4px 8px; min-height: 1.4em; }
</style>
<div class="bar">
  <button data-tool="wall" class="on">Walls</button><button data-tool="start">Start</button><button data-tool="goal">Goal</button>
  <select id="algo"><option value="1">A* (Manhattan)</option><option value="0">Dijkstra (h = 0)</option><option value="3">Weighted A* (3 × h)</option></select>
  <button id="step">Step</button><button id="play">Play</button><button id="reset">Reset search</button><button id="clear">Clear walls</button>
</div>
<canvas width="600" height="330"></canvas>
<div id="stats"></div>
<script>
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const CELL = 30, COLS = cv.width / CELL, ROWS = cv.height / CELL;
const wall = new Uint8Array(COLS * ROWS);
let start = { x: 2, y: 5 }, goal = { x: 17, y: 5 }, tool = 'wall';
for (let y = 2; y <= 8; y++) wall[y * COLS + 10] = 1;        // a starting wall
for (let x = 6; x <= 10; x++) { wall[2 * COLS + x] = 1; wall[8 * COLS + x] = 1; }
const id = (x, y) => y * COLS + x;
let S;   // search state

// A tiny binary heap ordered by (f, h, insertion order).
function less(a, b) { return a.f - b.f || a.h - b.h || a.n - b.n; }
function push(heap, item) {
  heap.push(item);
  let i = heap.length - 1;
  while (i > 0) { const p = (i - 1) >> 1; if (!less(heap[i], heap[p])) break; [heap[i], heap[p]] = [heap[p], heap[i]]; i = p; }
}
function pop(heap) {
  const top = heap[0], last = heap.pop();
  if (heap.length) {
    heap[0] = last;
    let i = 0;
    for (;;) {
      const l = 2 * i + 1, r = l + 1; let s = i;
      if (l < heap.length && less(heap[l], heap[s])) s = l;
      if (r < heap.length && less(heap[r], heap[s])) s = r;
      if (s === i) break;
      [heap[i], heap[s]] = [heap[s], heap[i]]; i = s;
    }
  }
  return top;
}

function resetSearch() {
  const w = Number(document.getElementById('algo').value);
  const h = (x, y) => w * (Math.abs(x - goal.x) + Math.abs(y - goal.y));
  S = { w, h, g: new Map([[id(start.x, start.y), 0]]), from: new Map(), closed: new Set(), heap: [], n: 0, done: false, path: null };
  push(S.heap, { x: start.x, y: start.y, f: h(start.x, start.y), h: h(start.x, start.y), n: S.n++ });
  playing = false; document.getElementById('play').textContent = 'Play';
  draw();
}

function step() {
  if (S.done) return;
  let cur;
  do { cur = S.heap.length ? pop(S.heap) : null; } while (cur && S.closed.has(id(cur.x, cur.y)));
  if (!cur) { S.done = true; return; }                  // open set empty: no path
  const k = id(cur.x, cur.y);
  S.closed.add(k);
  if (cur.x === goal.x && cur.y === goal.y) {
    S.done = true; S.path = [];
    for (let c = k; c !== undefined; c = S.from.get(c)) S.path.push(c);
    return;
  }
  for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]]) {
    const x = cur.x + dx, y = cur.y + dy;
    if (x < 0 || y < 0 || x >= COLS || y >= ROWS || wall[id(x, y)] || S.closed.has(id(x, y))) continue;
    const g = S.g.get(k) + 1, old = S.g.get(id(x, y));
    if (old !== undefined && old <= g) continue;
    S.g.set(id(x, y), g); S.from.set(id(x, y), k);
    const h = S.h(x, y);
    push(S.heap, { x, y, f: g + h, h, n: S.n++ });
  }
}

function draw() {
  ctx.fillStyle = '#161c27'; ctx.fillRect(0, 0, cv.width, cv.height);
  const openSet = new Set(S.heap.map((e) => id(e.x, e.y)));
  for (let y = 0; y < ROWS; y++) for (let x = 0; x < COLS; x++) {
    const k = id(x, y);
    ctx.fillStyle = wall[k] ? '#5b6475' : S.closed.has(k) ? '#2d4a7a' : openSet.has(k) ? '#3f8f6b' : '#1d2532';
    ctx.fillRect(x * CELL + 1, y * CELL + 1, CELL - 2, CELL - 2);
  }
  if (S.path) {
    ctx.strokeStyle = '#ffd34d'; ctx.lineWidth = 4; ctx.lineJoin = 'round'; ctx.beginPath();
    S.path.forEach((k, i) => { const x = (k % COLS + 0.5) * CELL, y = (Math.floor(k / COLS) + 0.5) * CELL; i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
    ctx.stroke();
  }
  for (const [p, c, t] of [[start, '#4dd2ff', 'S'], [goal, '#ff6b6b', 'G']]) {
    ctx.fillStyle = c; ctx.beginPath(); ctx.arc((p.x + 0.5) * CELL, (p.y + 0.5) * CELL, CELL * 0.38, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = '#10141c'; ctx.font = 'bold 14px system-ui'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
    ctx.fillText(t, (p.x + 0.5) * CELL, (p.y + 0.5) * CELL + 1);
  }
  const status = S.done ? (S.path ? `path cost ${S.path.length - 1}` : 'no path') : 'searching';
  document.getElementById('stats').textContent = `expanded ${S.closed.size}, open ${openSet.size}, ${status}`;
}

let playing = false, last = 0;
function loop(now) {
  if (playing && now - last > 25) { last = now; step(); draw(); if (S.done) { playing = false; document.getElementById('play').textContent = 'Play'; } }
  requestAnimationFrame(loop);
}
requestAnimationFrame(loop);

let painting = null;
function cellAt(e) {
  const r = cv.getBoundingClientRect();
  return { x: Math.floor((e.clientX - r.left) / r.width * COLS), y: Math.floor((e.clientY - r.top) / r.height * ROWS) };
}
function apply(c) {
  if (c.x < 0 || c.y < 0 || c.x >= COLS || c.y >= ROWS) return;
  const k = id(c.x, c.y), blocked = (p) => p.x === c.x && p.y === c.y;
  if (tool === 'wall') { if (!blocked(start) && !blocked(goal)) wall[k] = painting; }
  else if (!wall[k]) { if (tool === 'start' && !blocked(goal)) start = c; if (tool === 'goal' && !blocked(start)) goal = c; }
  resetSearch();
}
cv.addEventListener('pointerdown', (e) => { const c = cellAt(e); painting = wall[id(c.x, c.y)] ? 0 : 1; cv.setPointerCapture(e.pointerId); apply(c); });
cv.addEventListener('pointermove', (e) => { if (painting !== null && tool === 'wall') apply(cellAt(e)); });
cv.addEventListener('pointerup', () => { painting = null; });
document.querySelectorAll('[data-tool]').forEach((b) => b.addEventListener('click', () => {
  tool = b.dataset.tool;
  document.querySelectorAll('[data-tool]').forEach((o) => o.classList.toggle('on', o === b));
}));
document.getElementById('algo').addEventListener('change', resetSearch);
document.getElementById('step').addEventListener('click', () => { step(); draw(); });
document.getElementById('play').addEventListener('click', (e) => {
  if (S.done) resetSearch();
  playing = !playing; e.target.textContent = playing ? 'Pause' : 'Play';
});
document.getElementById('reset').addEventListener('click', resetSearch);
document.getElementById('clear').addEventListener('click', () => { wall.fill(0); resetSearch(); });
resetSearch();
</script>

Things to try: build a long wall with a gap far from the straight line and compare how many nodes each mode expands; wall the goal in completely and watch A* expand every reachable cell before reporting "no path". That last one matters in games: an unreachable goal is the worst case for any search, so check reachability cheaply first (for example with precomputed connected regions) before asking for a path.

A* in practice

  • Open set: a binary heap. Closed set and g: flat arrays indexed by cell id, reset with a "search generation" number instead of clearing them every time.
  • Cap the work: stop after N expansions and return the best partial path (the closed node with the lowest h), or continue next frame. See Field Notes: Performance.
  • Engines: Unity's AI Navigation, Unreal's navigation system (built on Recast/Detour) and Godot's NavigationServer all run A* over a navigation mesh rather than a grid.

Test yourself

What does A* order its open set by?

  1. g(n), the cost so far
  2. h(n), the estimate to the goal
  3. f(n) = g(n) + h(n)
  4. Insertion order

Why does an admissible heuristic guarantee the cheapest path?

  1. It is always exact
  2. It never overestimates, so a cheaper path can't be hiding behind a node with a higher f when the goal is popped
  3. It visits every node
  4. It makes the open set smaller

On the cup-shaped map, both searches found a path of cost 20. What did A* save?

  1. Path length
  2. The number of expanded nodes
  3. Memory for the path
  4. Nothing