A* (pronounced "A-star") finds a shortest path from a start to a specific goal by always expanding the node with the lowest f(n) = g(n) + h(n): the cost already paid to reach n plus an estimate of the cost still to go. With a heuristic that never overestimates, A* is guaranteed to return an optimal path, and with a good heuristic it explores a narrow corridor toward the goal instead of Dijkstra's ever-growing circle. It is the standard pathfinding algorithm in games, robotics and route planning.
Think of it like
Walking toward a landmark you can see
You are crossing an unfamiliar city on foot, heading for a tower visible above the rooftops. Dijkstra would explore every street in order of how far you have walked, in all directions equally. You instead prefer streets that are short so far and point toward the tower: you add the distance walked to the straight-line distance remaining. Straight-line distance never exaggerates the true walking distance, so you never wrongly dismiss the best route. That sum is g + h.
The core formula
- g(n)
- The cost of the best path found so far from the start to
n. Exactly Dijkstra'sdist[n]. - h(n)
- The heuristic: an estimate of the cheapest cost from
nto the goal, computed from problem knowledge (for example, coordinates). - f(n)
- The priority used by the open set. Lower
fis expanded first. - Open set
- The frontier: discovered nodes waiting to be expanded, kept in a min-priority queue by
f. - Closed set
- Nodes already expanded. With a consistent heuristic they never need to be reopened.
Dijkstra: f = g
- Ignores where the goal is
- Expands in circles of increasing distance
- Always optimal (non-negative weights)
- Finds distances to every vertex
Greedy best-first: f = h
- Ignores the cost already paid
- Rushes straight at the goal
- Often very fast
- Not optimal: can return long detours around obstacles
A*: f = g + h
- Balances cost so far and cost to go
- Optimal with an admissible heuristic
- Explores far fewer nodes than Dijkstra with a good
h - Built for one start and one goal
How it works
- 1
Initialize
g[start] = 0; push the start with priorityf = h(start). - 2
Pop the lowest f
Take the node
uwith the smallestffrom the open set. - 3
Goal test on pop
If
uis the goal, rebuild the path from parent pointers and stop. Testing when a node is first pushed can return a suboptimal path. - 4
Skip stale entries
If this entry's
fis larger thang[u] + h(u), a better entry was pushed later: ignore it. - 5
Relax neighbors
For each edge
u → v: ifg[u] + w < g[v], setg[v],parent[v] = u, and pushvwithf = g[v] + h(v).
Structurally this is Dijkstra's Algorithm with a different priority. The visualization above lets you draw walls and compare how many cells each algorithm explores before reaching the goal.
Heuristics for grids
| Heuristic | Formula (dx = |x₁ − x₂|, dy = |y₁ − y₂|) | Exact on an empty grid when |
|---|---|---|
| Manhattan | dx + dy | 4-directional moves, each costing 1 |
| Chebyshev | max(dx, dy) | 8-directional moves, diagonals costing 1 |
| Octile | max(dx, dy) + (√2 − 1) · min(dx, dy) | 8-directional moves, diagonals costing √2 |
| Euclidean | √(dx² + dy²) | Movement at any angle |
| Zero | 0 | Never informative: A* becomes Dijkstra |
Admissible and consistent heuristics
- Admissible
h(n) ≤ h*(n)for every node, whereh*(n)is the true remaining cost. The heuristic never overestimates.- Consistent (monotone)
h(n) ≤ c(n, n′) + h(n′)for every edge, andh(goal) = 0. The estimate never drops by more than the cost of a step: a triangle inequality.
Every consistent heuristic is admissible (sum the inequality along a shortest path to the goal), but not every admissible heuristic is consistent. All the grid heuristics above are consistent when matched to their movement rules. Consistency is what lets A* treat expanded nodes as final, exactly like Dijkstra's settled set.
Why A* is optimal
Suppose h is admissible and A* is about to pop the goal with cost C, while the optimal cost is C* < C. Some node n on an optimal path must still be in the open set with its optimal g(n) (the start was on that path, and each expansion pushes the next node with its optimal cost). Then:
Tie-breaking matters
On an open grid with Manhattan distance, every cell between the start and the goal has the same f. Without tie-breaking, A* may expand all of them. Breaking ties toward the smaller h (equivalently, the larger g) makes it dive toward the goal. Consider a 5 × 5 empty grid from one corner to the opposite one (path length 8):
| Search | Cells expanded | Why |
|---|---|---|
| BFS / Dijkstra | 24 to 25 | Everything closer than the goal is expanded first |
| A*, Manhattan, arbitrary ties | up to 25 | Every cell has f = 8, so the order is arbitrary |
| A*, Manhattan, ties toward smaller h | 9 | Only the cells on one shortest path |
| Greedy best-first | 9 | Same here, but it can be far from optimal once walls appear |
Weighted A* and other variants
Many games and robots prefer a good path now over the best path later. Weighted A* inflates the heuristic by ε > 1: it expands fewer nodes and, with an admissible h, the returned path costs at most ε times the optimum.
IDA*(iterative deepening on anfthreshold): memory is onlyO(depth), which made it the classic solver for the 15-puzzle.- Bidirectional search: run
A*from both ends; needs care to keep the meeting condition correct. D* LiteandLPA*: incremental replanning when the map changes, used on Mars rovers and mobile robots.- Jump Point Search: prunes symmetric paths on uniform-cost grids, often an order of magnitude faster than plain A*.
- Hierarchical pathfinding (
HPA*): plan on a coarse grid of map regions, then refine; standard in large game maps. - ALT and contraction hierarchies: road-network routing uses precomputed landmark distances as heuristics, or shortcuts in a preprocessed graph.
Beyond grids: puzzle state spaces
A* works on any implicit graph where you can estimate the distance to the goal (see Graph Fundamentals). For the 8-puzzle, each board is a node and the sum of Manhattan distances of each tile from its target square is admissible, because every move slides one tile one square. Counting misplaced tiles is admissible too but weaker, so it expands many more boards. Rubik's cube solvers use pattern databases: exact solution costs of sub-problems precomputed by BFS.
Complexity
| Case | Time | Space | Notes |
|---|---|---|---|
| Uninformed (h = 0) | O((V + E) log V) | O(V) | Identical to Dijkstra |
| Consistent heuristic | O((V + E) log V) | O(V) | Each node expanded at most once; usually far fewer |
| Grid with R × C cells | O(R·C log(R·C)) | O(R·C) | Upper bound; good heuristics explore a narrow corridor |
| Weighted A* (ε > 1) | O((V + E) log V) | O(V) | Fewer expansions; cost ≤ ε × optimal |
| IDA* on a tree of branching b, depth d | O(b^d) | O(d) | Trades repeated work for tiny memory |
The worst case matches Dijkstra; the practical gain depends entirely on how close h is to the true remaining cost.
Implementation
`#` cells are walls and every move costs 1. Manhattan distance is consistent here, ties prefer smaller `h`, and the goal test happens when the goal is popped. Returns the path as a list of cells, or an empty list.
import heapq
def astar_grid(grid: list[str], start: tuple[int, int], goal: tuple[int, int]) -> list[tuple[int, int]]:
rows, cols = len(grid), len(grid[0])
def h(r: int, c: int) -> int: # Manhattan distance to the goal
return abs(r - goal[0]) + abs(c - goal[1])
if grid[start[0]][start[1]] == "#" or grid[goal[0]][goal[1]] == "#":
return []
INF = float("inf")
g = [[INF] * cols for _ in range(rows)] # best known cost from start
parent = {}
g[start[0]][start[1]] = 0
heap = [(h(*start), h(*start), start)] # (f, h, cell): ties prefer smaller h
while heap:
f, _, (r, c) = heapq.heappop(heap)
if (r, c) == goal: # goal test on POP: cost is optimal
path = [goal]
while path[-1] != start:
path.append(parent[path[-1]])
return path[::-1]
if f > g[r][c] + h(r, c): # stale entry
continue
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != "#":
ng = g[r][c] + 1
if ng < g[nr][nc]:
g[nr][nc] = ng
parent[(nr, nc)] = (r, c)
hn = h(nr, nc)
heapq.heappush(heap, (ng + hn, hn, (nr, nc)))
return [] # goal unreachable
grid = ["....",
".##.",
"...."]
print(astar_grid(grid, (0, 0), (2, 3))) # 5 moves, e.g. along the top rowKey takeaways
- A* expands nodes by
f = g + h: cost so far plus an estimate of cost to go. Withh = 0it is Dijkstra. - An admissible heuristic (never overestimates) guarantees an optimal path; a consistent one also means each node is expanded at most once.
- Match the heuristic to the movement rules: Manhattan (4-way), Chebyshev or octile (8-way), Euclidean (any angle).
- Test for the goal when it is popped, not when it is pushed, and break ties toward smaller
h. - Weighted A* trades optimality for speed with a provable bound of
εtimes the optimal cost.
Common pitfalls
- Using an inadmissible heuristic (Manhattan with unit-cost diagonals) and silently getting suboptimal paths.
- Returning as soon as the goal is first discovered, before it is popped from the open set.
- Leaving out tie-breaking on open grids, so A* expands nearly as many cells as Dijkstra.
- Closing nodes permanently with an inconsistent heuristic, which can miss the optimal path.
- Expecting A* to help when you need distances to every vertex; it is built for a single goal.
Interview tips
- Define
g,handfprecisely, then state that A* withh = 0reduces to Dijkstra; it shows you understand both. - Be ready to explain admissibility with a concrete counterexample (Manhattan on an 8-directional grid).
- Offer A* as an optimization of a correct BFS or Dijkstra solution once the baseline is written.
Real-world applications
- Unit and NPC pathfinding in video games (often with Jump Point Search or hierarchical maps).
- Robot and drone motion planning, including incremental variants like D* Lite.
- Route planning in maps and navigation, with landmark-based heuristics.
- Solving puzzles such as the 8-puzzle, 15-puzzle and Sokoban.
- Natural language processing and speech recognition decoders (A* over lattices).
Practice problems
Test yourself
On an 8-directional grid where a diagonal step costs 1, which heuristic is NOT admissible?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.