A* search algorithm

Also known as: A-star

On this page 7

The A* search algorithm (pronounced A-star) is a best-first graph search that finds a lowest-cost path from a start node to a goal node by ranking candidates with the function f(n) = g(n) + h(n), where g(n) is the known cost from the start and h(n) is a heuristic estimate of the remaining cost. Among algorithms used in programming, it is the standard choice for pathfinding when a good distance estimate is available.

A* was published in 1968 by Peter Hart, Nils Nilsson and Bertram Raphael for robot navigation research. Its lasting value lies in a precise guarantee: with an admissible heuristic, it returns an optimal path while usually expanding far fewer nodes than uninformed searches.

How A* expands the search frontier

A* keeps an open set of discovered but unexpanded nodes, normally stored in a priority queue ordered by f(n), and a closed set of nodes already expanded. At each step it removes the node with the smallest f value, stops if that node is the goal, and otherwise examines each neighbor.

For every neighbor, the algorithm computes a tentative g value as the current node cost plus the edge weight. If this value improves the best known cost, A* records the current node as the parent, updates g and f, and inserts or reprioritizes the neighbor in the open set. When the goal is removed from the queue, following parent pointers backward reconstructs the path.

The three quantities that drive every decision are summarized below.

ValueMeaningSource
g(n)Exact cost from start to n along the best path foundAccumulated edge weights
h(n)Estimated cost from n to the goalProblem-specific heuristic
f(n)Estimated total cost of a path through nSum of g(n) and h(n)
Parent pointerPredecessor on the best known pathUpdated on each improvement
Core values used by A*

Heuristic properties that guarantee optimal paths

The quality and correctness of A* depend almost entirely on the heuristic function. Two formal properties define whether the result is guaranteed to be optimal and whether nodes ever need to be reopened.

A heuristic is admissible when it never overestimates the true remaining cost. Admissibility guarantees an optimal path in tree search. A heuristic is consistent, or monotone, when h(n) is at most the edge cost to a neighbor plus that neighbor’s h value. Consistency implies admissibility and ensures that each node is expanded at most once in graph search, which keeps the closed set simple.

Common heuristics for grid and map problems are compared below; the right one matches the allowed movement model.

HeuristicFormula ideaBest movement modelAdmissible when
Manhattan distanceSum of horizontal and vertical offsetsFour-direction gridsDiagonal moves are not allowed
Octile distanceStraight moves plus diagonal moves at cost about 1.414Eight-direction gridsDiagonal cost matches the formula
Chebyshev distanceLargest of the two offsetsEight directions at equal costDiagonal moves cost the same as straight ones
Euclidean distanceStraight-line distanceFree movement or road mapsEdge costs are at least geometric length
ZeroAlways 0Any graphAlways, but no guidance
Typical heuristics for grid pathfinding

A more informed heuristic, one that is larger while staying admissible, expands fewer nodes. The ideal is the exact remaining cost, which would let A* walk straight to the goal, but computing it usually costs as much as solving the problem.

A* sits between uninformed search and pure greedy guessing, and several familiar algorithms are special cases of it. Setting h(n) to zero turns A* into Dijkstra’s algorithm, while ignoring g(n) turns it into greedy best-first search.

AlgorithmPriority usedOptimal resultTypical node expansions
Breadth-first searchNumber of edgesOnly with equal edge costsVery high
Dijkstra’s algorithmg(n) onlyYes, with nonnegative weightsHigh, spreads in all directions
Greedy best-first searchh(n) onlyNoLow, but can wander
A* searchg(n) + h(n)Yes, with an admissible heuristicLow to moderate
Weighted A*g(n) + w times h(n)Bounded by factor wLower than A*
How A* relates to neighboring algorithms

The choice is therefore a trade-off between guidance and certainty. Dijkstra is preferable when there is no meaningful estimate or when distances to many targets are needed, while A* wins for single-pair queries with a good heuristic.

Complexity and memory behavior

The time complexity of A* depends on the heuristic rather than on a single closed formula. With a binary heap and a consistent heuristic, the worst case matches Dijkstra at roughly O(E log V) for a graph with V vertices and E edges, but a strong heuristic often limits work to a narrow corridor around the optimal path.

The practical bottleneck is usually space complexity. A* stores every generated node in the open or closed set, so memory grows with the explored area and can become prohibitive in huge state spaces such as puzzles with billions of configurations. This is why memory-bounded variants were developed.

VariantKey changeMain benefit
IDA*Depth-first iterations with a rising f limitLinear memory use
Weighted A*Inflates h(n) by a factor above 1Faster, bounded suboptimal paths
Bidirectional A*Searches from start and goal at onceFewer expansions on large maps
D* LiteRepairs the previous solutionFast replanning as the map changes
Jump point searchSkips symmetric grid pathsLarge speedups on uniform grids
Common A* variants and when to use them

Implementation pitfalls

Most A* bugs come from small implementation details rather than from the idea itself. The following mistakes regularly produce wrong or slow results.

  • Overestimating heuristic: using a distance that ignores cheaper diagonal or road links breaks optimality without any visible error.
  • Wrong heuristic scale: mixing kilometers in h(n) with minutes in g(n) silently distorts the ranking.
  • Stale queue entries: when a node is reinserted with a better f value, the old entry must be skipped or lazily discarded when popped.
  • Tie-breaking ignored: many equal f values on open grids cause broad exploration; preferring higher g values reduces wasted expansions.
  • Negative edge weights: A* assumes nonnegative costs, so such graphs need a different method such as Bellman–Ford.
  • Early stopping on discovery: the search must end when the goal is removed from the queue, not when it is first seen.

The short version

A* is a method for finding the shortest or cheapest route between two points. At every step it asks two questions: how far have I already traveled, and roughly how far is it still to the goal?

It is like crossing an unfamiliar city with a compass. You keep track of the distance you have walked, and you prefer streets that point toward your destination. As long as your guess about the remaining distance is never too optimistic in the wrong direction, never larger than reality, you are guaranteed to find the best route while skipping most of the streets that lead away.

Where it makes a difference

A game studio builds a strategy game in which up to 200 units move across a map of 512 by 512 tiles, with forests that cost three times as much to cross as open ground. Each unit needs a path whenever the player issues an order, and the whole frame must finish in about 16 milliseconds.

Using Dijkstra from each unit would explore a large circle of tiles around every start point. The developers instead use A* with the octile distance heuristic, scaled to the cheapest terrain cost so it stays admissible, and break ties in favor of nodes closer to the goal. A typical query now expands only a few thousand tiles instead of tens of thousands.

The outcome is that units follow optimal routes around forests while pathfinding stays within the frame budget. For long cross-map orders, the team adds weighted A* with a factor of 1.2, accepting paths at most 20 percent longer in exchange for noticeably faster planning.