12. A* Search
Dijkstra plus a heuristic — find the shortest path by looking in the right direction
Dijkstra's algorithm finds the shortest path. It's correct, it's elegant, and it has one glaring inefficiency: it explores in every direction equally. If you're navigating from New York to Boston, Dijkstra happily searches south toward Miami before it thinks to head northeast.
A* fixes this by adding a simple idea: use an estimate of how far you still have to go. Instead of blindly expanding the cheapest-so-far node, A* expands the node that looks most promising when you factor in both the cost already paid and the estimated remaining cost. Published by Peter Hart, Nils Nilsson, and Bertram Raphael in 1968, it remains the gold standard for informed search.
The Key Idea: f(n) = g(n) + h(n)
A*'s Evaluation Function
For every node n, A* computes:
- g(n) — the actual cost from the start to
n(what Dijkstra uses alone) - h(n) — the heuristic estimate of the cost from
nto the goal - f(n) = g(n) + h(n) — the estimated total cost of the cheapest path through
n
A* always expands the node with the lowest f(n). This steers the search
toward the goal while still guaranteeing optimality — as long as the heuristic is well-chosen.
When h(n) = 0 for all nodes, f(n) = g(n), and A* degenerates into Dijkstra.
The heuristic is what gives A* its power.
What Makes a Good Heuristic
Not any estimate will do. For A* to guarantee the shortest path, the heuristic must satisfy specific properties:
| Property | Definition | Why it matters |
|---|---|---|
| Admissible | h(n) <= actual cost for every node |
Never overestimates, so A* won't skip the true shortest path |
| Consistent | h(n) <= cost(n, n') + h(n') for every edge |
Ensures f-values never decrease along a path (triangle inequality), so nodes don't need re-expansion |
Consistency implies admissibility (but not the other way around). In practice, most natural heuristics — like straight-line distance on a map — are both.
Common Heuristics for Grid Pathfinding
| Heuristic | Formula | Best for |
|---|---|---|
| Manhattan | ` | x1 - x2 |
| Euclidean | sqrt((x1-x2)^2 + (y1-y2)^2) |
Any-angle movement (continuous space) |
| Chebyshev | `max( | x1-x2 |
The key rule: match the heuristic to the movement model. On a 4-directional grid, Manhattan distance is exact for open space, making it a tight admissible heuristic. Use Euclidean if movement is unconstrained. Use Chebyshev for king-moves on a chessboard.
A Simple Grid Example
Consider a 5x5 grid. Start is top-left (0,0), goal is bottom-right
(4,4). Movement is 4-directional, each step costs 1. A wall blocks the
direct path.
The grid (W = wall, S = start, G = goal)
S . . . .
. . W . .
. . W . .
. . W . .
. . . . G
Dijkstra explores (all nodes with cost <= 8):
Dijkstra visits: 21 nodes
It fans out in all directions, exploring
left and upward even though the goal is
down and to the right.
A* with Manhattan distance explores:
A* visits: 12 nodes
It heads toward the goal, only detouring
around the wall when forced to. Nearly
half as many nodes explored.
Both find the same optimal path of length 8. A* just wastes less time looking in the wrong direction.
Dijkstra vs A*: Side by Side
| Property | Dijkstra | A* |
|---|---|---|
| Expansion order | Lowest g(n) | Lowest f(n) = g(n) + h(n) |
| Nodes explored (above grid) | 21 | 12 |
| Optimal? | Yes, always | Yes, with admissible heuristic |
| Complete? | Yes | Yes |
| Uses domain knowledge? | No | Yes (the heuristic) |
| When h(n) = 0 | — | Becomes Dijkstra |
The Algorithm Step by Step
A* maintains two sets: an open set (nodes to explore, typically a min-heap keyed by f-value) and a closed set (nodes already fully explored).
-
Initialize
Add the start node to the open set. Set
g(start) = 0andf(start) = h(start). The closed set is empty. -
Pick the best node
Remove the node with the lowest
f-value from the open set. Call itcurrent. -
Goal test
If
currentis the goal, reconstruct the path by following parent pointers and return it. Done. -
Expand neighbors
For each neighbor of
current: computetentative_g = g(current) + cost(current, neighbor). If this is less than the neighbor's currentg-value, update itsg, computef = g + h, set its parent tocurrent, and add it to the open set (if not already there). -
Mark as explored
Add
currentto the closed set. Skip it if encountered again. -
Repeat
Go back to step 2. If the open set is empty and the goal hasn't been reached, no path exists.
Pseudocode
function a_star(start, goal, neighbors, cost, h):
open_set = min-heap ordered by f
came_from = {}
g = {start: 0}
f = {start: h(start)}
open_set.add(start)
closed = {}
while open_set is not empty:
current = open_set.pop_min()
if current == goal:
return reconstruct_path(came_from, current)
closed.add(current)
for each neighbor in neighbors(current):
if neighbor in closed:
continue
tentative_g = g[current] + cost(current, neighbor)
if tentative_g < g.get(neighbor, infinity):
came_from[neighbor] = current
g[neighbor] = tentative_g
f[neighbor] = tentative_g + h(neighbor)
if neighbor not in open_set:
open_set.add(neighbor)
return failure // no path exists
What Happens with a Bad Heuristic
The quality of the heuristic controls the behavior of A*:
| Heuristic quality | Effect |
|---|---|
| h(n) = 0 | A* becomes Dijkstra — correct but explores everything equally |
| h(n) <= actual cost (admissible) | A* is optimal. The tighter h is, the fewer nodes explored |
| h(n) = actual cost (perfect) | A* goes straight to the goal with no wasted exploration |
| h(n) > actual cost (overestimates) | A* may find a suboptimal path. It becomes greedy, chasing the heuristic's advice even when it's wrong |
The admissibility tradeoff
A more informed (larger but still admissible) heuristic explores fewer nodes. But computing a tighter heuristic may itself be expensive. The art of A* is choosing an h(n) that's cheap to compute yet close to the true cost.
Complexity
A*'s complexity depends heavily on the heuristic quality:
| Scenario | Time | Space |
|---|---|---|
| Perfect heuristic | O(d) where d = path length | O(d) |
| Good heuristic | Much less than Dijkstra in practice | O(nodes explored) |
| h(n) = 0 (worst case) | O((V + E) log V) — same as Dijkstra | O(V) |
The space complexity is often the practical bottleneck: A* must store every explored node and the entire open set in memory. For very large graphs, variants like IDA* (iterative deepening A*) trade time for space.
Where A* Is Used
| Application | How it uses A* |
|---|---|
| Video game pathfinding | NPCs navigate around obstacles on tile maps or nav meshes. A* with Manhattan or Euclidean heuristic is the industry standard |
| Robotics | Mobile robots plan collision-free paths through physical space, often on discretized grids |
| GPS navigation | Route planners use A* (or its variants like ALT) with geographic distance as the heuristic |
| 15-puzzle solver | A* with "Manhattan distance of all tiles" heuristic solves the sliding puzzle optimally |
| Rubik's cube | Pattern database heuristics with IDA* can solve it in the provably fewest moves |
| Natural language parsing | A* search over parse trees finds the most probable parse efficiently |
Key Takeaways
- A* extends Dijkstra by adding a heuristic estimate h(n) of remaining cost:
f(n) = g(n) + h(n) - An admissible heuristic (never overestimates) guarantees A* finds the optimal path
- A consistent heuristic additionally prevents node re-expansion, making A* more efficient
- With h(n) = 0, A* degrades to Dijkstra; with a perfect h, it goes straight to the goal
- Match the heuristic to the movement model: Manhattan for 4-directional, Euclidean for any-angle, Chebyshev for 8-directional
- A* is the workhorse of game AI, robotics, and puzzle solving — anywhere you have a goal and a way to estimate distance to it
Try It Yourself — A* vs Dijkstra
Click cells to toggle walls. Drag the S (start) and G (goal) to reposition them. Hit Run to watch both algorithms search simultaneously — A* in teal, Dijkstra in orange. Compare how many nodes each explores to find the same shortest path.
A* Search
Dijkstra
A* is a beautiful demonstration of how a little domain knowledge goes a long way. Dijkstra searches blind; A* searches with purpose. The heuristic doesn't have to be perfect — it just has to point roughly in the right direction. That simple idea, f = g + h, transformed pathfinding from an exhaustive search into a targeted one, and it remains one of the most important algorithms in computer science.