A* pathfinding visualizer
A* finds a shortest path by always exploring the cell with the lowest f = g + h: the steps taken so far plus an estimate of the steps left. Draw walls, move the start and goal, and compare how far the search spreads with each heuristic.
start goal wall open set expanded path
Press Play or Step. Manhattan will search from the green cell to the dark one.
| Heuristic | Expanded | Path |
|---|---|---|
| None (Dijkstra) | 282 | 29 |
| Euclidean | 241 | 29 |
| Manhattan | 134 | 29 |
| 2 × Manhattan (weighted) | 69 | 29 |
The shortest path is 29 steps, checked by breadth-first search. Every step costs 1 and moves are up, down, left or right. Hover over a cell to see its g, h and f.
- g
- steps from the start, as found so far
- h
- estimate of steps to the goal
- f = g + h
- lowest is expanded next
How to use the simulator
The search runs as soon as anything changes; press Play to watch it, or Step through it one event at a time. Light cells are in the open set, waiting to be expanded; darker cells have been expanded; the path appears at the end. Click or drag on the grid to draw or erase walls, or switch the click mode to move the start or goal. The table beside the grid runs all four heuristics on the same grid.
Try these:
- On the Empty layout, compare None with Manhattan. Dijkstra's algorithm spreads out in a diamond until it reaches the goal; Manhattan A* walks almost straight to it.
- Load the U-shaped trap. The start sits inside a cup that opens away from the goal. The heuristic pulls the search into the back of the cup, and A* has to fill it before it finds the way round.
- Load Detour and pick 2 × Manhattan. It returns a path 10 steps longer than the shortest, and on this layout it does not even save work: it expands 136 cells against 133 for plain Manhattan. Overestimating breaks the guarantee.
- Wall the goal off completely. Every heuristic then has to expand every cell it can reach before it can say there is no path.
The search code is tested against breadth-first search on thousands of random grids: with None, Euclidean and Manhattan it always returns the shortest length; with 2 × Manhattan it never returns a path more than twice as long; and Manhattan never expanded more cells than Dijkstra's algorithm.
What is A*?
A* (pronounced "A star") is an algorithm for finding a shortest path between two points in a graph: cells on a grid, intersections on a road map, states of a puzzle. It works like Dijkstra's algorithm but adds an estimate of the distance still to go, called the heuristic, so that it explores toward the goal first.
The heuristic does not need to be exact. As long as it never overestimates the remaining cost, A* still returns a shortest path; the better the estimate, the fewer places it has to look. A heuristic of zero makes A* identical to Dijkstra's algorithm, and a perfect heuristic would let it walk straight down the shortest path.
How it works
A* keeps two sets. The open set holds nodes that have been reached but not yet explored, usually in a priority queue such as a binary heap. The closed set holds nodes already expanded. For each node it records g, the cost of the best path found to it so far, and a parent pointer to the node it was reached from.
- Put the start in the open set with g = 0.
- Take the node with the smallest f = g + h out of the open set. If it is the goal, stop.
- Otherwise expand it: for each neighbour, compute g through this node. If that is lower than the neighbour's current g, record the new g and parent and put the neighbour in the open set.
- Move the node to the closed set and go back to step 2. If the open set runs out, there is no path.
The path is read back by following parent pointers from the goal. Two details matter in practice. The test for the goal happens when the goal is taken out of the open set, not when it is first reached, because a cheaper route may still be waiting. And when several nodes share the lowest f, preferring the one with the larger g (further along its path) reduces the number of expansions on grids, where ties are common; the simulator does this.
Heuristics
A heuristic is admissible if it never overestimates the true remaining cost, and consistent if it never drops by more than the cost of a step: h(n) ≤ cost(n, m) + h(m) for every neighbour m. Admissibility guarantees a shortest path; consistency also guarantees that each node is expanded at most once, which is why simple implementations like this one can close a node for good.
On a grid the right heuristic depends on the moves allowed. With four-way moves of cost 1, Manhattan distance, |Δrow| + |Δcol|, is exact when there are no walls, so it is the best admissible choice. Euclidean distance is also admissible but smaller, so it guides the search less. With eight-way moves, octile or Chebyshev distance plays the role Manhattan plays here. A good general recipe is relaxation: drop a constraint of the real problem, such as walls, and use the cost of the easier problem as h.
The counts below come from running the simulator's code on its fixed layouts.
| Layout | Shortest | None | Euclidean | Manhattan | 2 × Manhattan |
|---|---|---|---|---|---|
| Walls | 29 | 282 | 241 | 134 | 69 |
| U-shaped trap | 23 | 277 | 119 | 67 | 67 |
| Detour | 29 | 222 | 186 | 133 | 136 (path 39) |
| Empty | 17 | 225 | 18 | 18 | 18 |
Cells expanded for each heuristic; a path length is shown only where it is longer than the shortest. The trap shows the limit of a heuristic that ignores walls. Manhattan beats Dijkstra there (67 cells against 277), but it expands 67 cells for a path of 23 steps, because the estimate keeps pulling it into the back of the cup. On the Empty layout it expands 18, exactly the cells on the path.
Weighted A*
Multiplying the heuristic by a weight w greater than 1 makes A* greedier: it trusts the estimate more and the cost so far less, and usually expands fewer nodes. The price is optimality. The path found is never more than w times the shortest, a bound that goes back to Ira Pohl's work on weighted heuristic search in 1970. On the Walls layout, w = 2 expands 69 cells instead of 134 and still finds a shortest path. On the Detour layout it follows the estimate into a long way round: 39 steps instead of 29, after expanding 136 cells against 133 for plain Manhattan. The saving is likely, not guaranteed; the bound on path length is.
Anytime variants such as ARA* (Likhachev, Gordon and Thrun, 2003) start with a large weight to get a path quickly, then lower it and improve the path while time allows, reusing earlier work. They are used in robot motion planning, where a good path now is worth more than the best path later.
A* and Dijkstra's algorithm
With h = 0, f equals g and A* is exactly Dijkstra's algorithm stopped at the goal. With a consistent heuristic, A* is equivalent to running Dijkstra's algorithm on a graph whose edge costs have been adjusted by the heuristic, which is one way to see why it stays correct. Rina Dechter and Judea Pearl showed in 1985 that, among algorithms given the same consistent heuristic, A* is optimal in the number of nodes it must expand, up to how ties are broken.
Dijkstra's algorithm is still the right choice when there is no useful estimate, or when the distances to many destinations are needed at once. A* is for one start and one goal with a sensible way to estimate the distance between them.
Variants
| Variant | Introduced | What it changes |
|---|---|---|
| IDA* | Richard Korf, 1985 | Depth-first search with a rising limit on f. Uses memory proportional to the path length instead of the number of nodes, at the cost of re-expanding nodes; used for puzzles such as the 15-puzzle. |
| Bidirectional search | Ira Pohl, 1971 | Searches from both ends and stops when the frontiers meet. The stopping rule is subtle: the first meeting point is not always on a shortest path. |
| D* Lite | Sven Koenig and Maxim Likhachev, 2002 | Replans efficiently when the map changes, reusing the previous search; designed for robots exploring unknown terrain. |
| Jump point search | Daniel Harabor and Alban Grastien, 2011 | For uniform-cost grids with eight-way moves: skips over cells that symmetric paths would cover, expanding far fewer nodes with the same result. |
| ALT | Andrew Goldberg and Chris Harrelson, 2005 | A* with landmarks: precomputed distances to a few landmark nodes give a much tighter admissible heuristic on road networks than straight-line distance. |
Where it is used
- Games. Game characters usually navigate over a navigation mesh, a graph of walkable polygons, rather than a grid. Recast Navigation's Detour library, used by several game engines, finds paths over such a mesh with A* and a straight-line heuristic, scaled by 0.999 in its source so that it stays slightly below the true distance.
- Robotics. A* was created for SRI's Shakey robot, and grid and lattice versions of it, along with D* Lite and anytime variants, remain common in mobile-robot planners.
- Road routing. Plain A* with straight-line distance helps little on continental road networks, because the estimate is weak. Routing engines rely on preprocessing instead, such as contraction hierarchies or landmarks (ALT), and search the resulting graph with bidirectional Dijkstra or A*.
- Puzzles and planning. Optimal solvers for sliding-tile puzzles and similar problems use A* or IDA* with heuristics computed from simplified versions of the puzzle (pattern databases).
History
A* was developed at the Stanford Research Institute for Shakey, a mobile robot that planned its own movements. Nils Nilsson first proposed a heuristic version of Dijkstra's algorithm (called A1), Bertram Raphael improved it (A2), and Peter Hart supplied the proof of when such an algorithm is guaranteed to find a shortest path. Their paper, "A Formal Basis for the Heuristic Determination of Minimum Cost Paths", appeared in IEEE Transactions on Systems Science and Cybernetics in 1968, and the best version of the algorithm became A*.
Later work refined the theory, including Pohl's weighted search in 1970, Korf's IDA* in 1985 and Dechter and Pearl's 1985 optimality results, and extended it to changing maps, limited memory and huge graphs.
A* questions and answers
What is the A* algorithm?
A* is a shortest-path search algorithm. It keeps a priority queue of places to explore, ordered by f = g + h, where g is the known cost from the start and h is an estimate of the remaining cost to the goal. It always expands the cell or node with the smallest f, so it heads toward the goal instead of spreading evenly in every direction. Peter Hart, Nils Nilsson and Bertram Raphael published it in 1968.
What is the difference between A* and Dijkstra’s algorithm?
Dijkstra’s algorithm is A* with h = 0: it orders the queue by distance from the start alone, so it explores in every direction until it reaches the goal. A* adds the estimate h, which pulls the search toward the goal. Both find the shortest path if h never overestimates. On this page’s open grid, Dijkstra expands 225 cells and Manhattan A* 18.
What makes a heuristic admissible?
A heuristic is admissible if it never overestimates the true remaining cost. With an admissible heuristic A* always returns a shortest path. Manhattan distance is admissible on a grid with four-way moves, straight-line distance is admissible on any map where you cannot travel faster than in a straight line, and h = 0 is admissible but gives no guidance.
What is a consistent heuristic?
A heuristic is consistent (or monotone) if, for every step from n to a neighbour m, h(n) ≤ cost(n, m) + h(m). Consistency implies admissibility, and it guarantees that when A* first expands a node it has already found the best path to it, so no node needs expanding twice. Manhattan and Euclidean distance are consistent on a grid; doubling Manhattan is not.
Is A* always optimal?
Only if the heuristic is admissible (and, if nodes are never re-expanded, consistent). With an overestimating heuristic it can return a longer path. Weighted A* multiplies h by w > 1 on purpose: it usually expands fewer nodes and its path is at most w times longer than the shortest. In the Detour layout on this page, 2 × Manhattan finds a path of 39 steps where the shortest is 29.
Which heuristic should I use on a grid?
Match the heuristic to the moves allowed. With four-way moves of cost 1, use Manhattan distance. With eight-way moves where diagonals cost √2, use octile distance; if diagonals cost 1, use Chebyshev distance. Euclidean distance is admissible in all these cases but underestimates more, so A* expands more cells than it needs to.
How fast is A*?
In the worst case, such as when the goal is unreachable or the heuristic gives no guidance, A* expands every reachable node, like Dijkstra: O(E log V) time with a binary heap and O(V) memory. With a good heuristic it expands far fewer. Memory, more than time, is usually what limits it on very large graphs.
Further reading
- Hart, Nilsson and Raphael, 1968A Formal Basis for the Heuristic Determination of Minimum Cost PathsThe original A* paper, with the proof of optimality.
- Dechter and Pearl, 1985Generalized best-first search strategies and the optimality of A*In what sense A* does the least work possible.
- Amit Patel, Red Blob GamesIntroduction to the A* AlgorithmAn interactive introduction from breadth-first search to A*.
- Amit PatelHeuristicsChoosing grid heuristics, tie-breaking and weighting, in practical detail.
- Harabor and Grastien, 2011Online Graph Pruning for Pathfinding on Grid MapsJump point search.
- Koenig and Likhachev, 2002D* LiteIncremental replanning when the map changes.