AlgoFrames

A* search with heuristics

A* adds a heuristic estimate of the remaining distance to Dijkstra’s cost. A good heuristic aims the search at the goal and expands fewer cells.

Before you start: Floyd-Warshall: all pairs.

The idea

A route planner needs the way from S to T only. Searching in every direction wastes work on cells far from T.

Intuition

Dijkstra expands cells in rings of equal g around S. It expands 18 cells here, including ones that lead away from T.

Dijkstra knows only the cost so far, g. It has no idea where T is.

A* also estimates the rest of the way with h, here the Manhattan distance to T. Each open cell gets f = g + h.

On a grid with four moves, the Manhattan distance |Δrow| + |Δcol| never exceeds the real remaining steps.

A* always expands the open cell with the smallest f; on equal f, the smaller h goes first. It reaches T after 9 expansions, not 18.

Complexity

In the worst case A* expands as much as Dijkstra: O(E log V). With a good h on an open grid it expands only about 2n cells.

A heap holds the open cells, so each push or pop costs O(log V). The heuristic changes how many cells are expanded, not the cost per cell.

Pitfalls

An h that overestimates can return a longer route. Here h = 3 × Manhattan finds 8 steps, but 6 is possible.

A* is exact only when h is admissible: it never exceeds the true remaining cost.

With diagonal moves, Manhattan distance overestimates. Use the larger of |Δrow| and |Δcol| instead.

Variations

With h = 0, A* is Dijkstra. With f = h only it is greedy search: on this new grid it heads up and needs 9 steps, A* 7.

Code

Pseudocode

g[start] ← 0; open ← {start}, with f = h(start)
while open not empty
  cell ← the open cell with the smallest f = g + h
  if cell is already expanded: skip it
  if cell is the goal: return g[cell]
  mark cell expanded
  for each neighbor next that is not a wall
    if g[cell] + 1 < g[next]
      g[next] ← g[cell] + 1
      add next to open with f = g[next] + h(next)
return −1

Python

import heapq
def astar(grid, start, goal):
    rows, cols = len(grid), len(grid[0])
    def h(r, c):
        return abs(r - goal[0]) + abs(c - goal[1])
    if grid[start[0]][start[1]] == 1 or grid[goal[0]][goal[1]] == 1:
        return -1
    g = {tuple(start): 0}
    heap = [(h(*start), h(*start), start[0], start[1])]
    closed = set()
    while heap:
        f, _, r, c = heapq.heappop(heap)
        if (r, c) in closed:
            continue
        if r == goal[0] and c == goal[1]:
            return g[(r, c)]
        closed.add((r, c))
        for nr, nc in ((r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0:
                ng = g[(r, c)] + 1
                if ng < g.get((nr, nc), float("inf")):
                    g[(nr, nc)] = ng
                    heapq.heappush(heap, (ng + h(nr, nc), h(nr, nc), nr, nc))
    return -1

JavaScript

function astar(grid, start, goal) {
  const rows = grid.length, cols = grid[0].length;
  const h = (r, c) => Math.abs(r - goal[0]) + Math.abs(c - goal[1]);
  if (grid[start[0]][start[1]] === 1 || grid[goal[0]][goal[1]] === 1) return -1;
  const g = new Map([[start[0] * cols + start[1], 0]]);
  const closed = new Set();
  const open = [[h(start[0], start[1]), h(start[0], start[1]), start[0], start[1]]];
  while (open.length > 0) {
    open.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
    const [, , r, c] = open.shift();
    const k = r * cols + c;
    if (closed.has(k)) continue;
    if (r === goal[0] && c === goal[1]) return g.get(k);
    closed.add(k);
    for (const [nr, nc] of [[r - 1, c], [r, c + 1], [r + 1, c], [r, c - 1]]) {
      if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] === 1) continue;
      const nk = nr * cols + nc, ng = g.get(k) + 1;
      if (closed.has(nk) || ng >= (g.get(nk) ?? Infinity)) continue;
      g.set(nk, ng);
      open.push([ng + h(nr, nc), h(nr, nc), nr, nc]);
    }
  }
  return -1;
}

Cost at a glance

TimeO(E log V) worst; less with a good heuristic
SpaceO(V)
InputNon-negative weights and an admissible heuristic
OutputShortest path to one target

Practice problems (3)

Admissible heuristic Warm-up

A robot moves on a grid one step up, down, left or right. Each step costs 1. You run A* to the goal at (gr, gc). Which heuristic h(r, c) guarantees the shortest route?

Compare expansions with Dijkstra Standard

Dijkstra and A* both search from S to T on the same grid. Watch each search expand cells, then type how many cells each one expanded, T included.

Implement A* on a grid Standard

A grid holds 0 for an open cell and 1 for a wall. Move one step up, down, left or right onto open cells, each step costing 1.

Return the fewest steps from start to goal (each given as [row, col]), or -1 if the goal cannot be reached. Use A* with the Manhattan distance as the heuristic.

Next on the path: Kruskal's algorithm