A* Search
A* finds a cheapest path to one goal. It always expands the node with the smallest f = g + h: the cost paid so far plus an estimate of the cost still to go. If the estimate never overestimates, the first time the goal is popped its cost is optimal.
How the A Star Algorithm Works
- Put the start in the open list with g = 0 and f = h(start)
- Pop the node with the smallest f; skip it if it is a stale entry
- If it is the goal, stop and follow parent links back to the start
- For each neighbour, if g + edge cost beats its best g so far, record the new g and parent and push it with f = g + h
- If the open list empties, the goal is unreachable
The A star algorithm (written A*) finds the cheapest path from a start to one goal in a graph with non-negative edge costs. Peter Hart, Nils Nilsson and Bertram Raphael published it in 1968 for the Shakey robot at SRI.
Each node n gets two numbers. g(n) is the cost of the best path found from the start to n, which is known exactly. h(n) is a heuristic: an estimate of the cost from n to the goal, such as straight-line distance on a map. The A* search algorithm always expands the node with the smallest f(n) = g(n) + h(n), its best guess of the total cost of a route through n.
In the tracer's grid the straight line from S to G runs through a swamp. Entering it would give f = 11, while stepping around gives f = 9, so A* goes around and never expands a swamp cell. It finds the cost-9 route after 12 expansions.
- g = known cost so far; h = estimate of the rest; f = g + h
- Keep a best-g table and a parent table next to the heap
- Practice: Shortest Path in Binary Matrix, Open the Lock
Admissible and Consistent Heuristics
An admissible heuristic never overestimates: h(n) is at most the true cheapest cost from n to the goal. That is what makes A* optimal. When the goal comes off the open list with cost C, every node still waiting has f ≥ C, and because h is optimistic, f is a lower bound on any route through that node, so none of them can lead to something cheaper.
A consistent heuristic (also called monotone) satisfies h(u) ≤ cost(u, v) + h(v) for every edge, with h(goal) = 0: the estimate can drop by at most the cost of a step. Every consistent heuristic is admissible. With consistency, f never decreases along a path, so the first time a node is popped its g is final and it never has to be expanded again.
With a heuristic that is admissible but not consistent, a node can be popped and later reached more cheaply. An implementation that permanently closes popped nodes can then return a wrong answer; it must allow a node to be reopened when its g improves.
Stop when the goal is popped, not when it is first pushed. The first route to reach the goal may not be the cheapest; a cheaper one can still be waiting in the open list.
- Admissible: h(n) ≤ true remaining cost, so the answer is optimal
- Consistent: h(u) ≤ cost(u, v) + h(v), so popped nodes are final
- Overestimating h can return a more expensive path
Choosing a Heuristic
A good heuristic is cheap to compute, never overestimates, and is as close to the real cost as possible: the closer it is, the fewer nodes A* expands. A reliable way to build one is to relax the problem, drop a rule, and use the exact cost of the easier problem. Ignoring walls gives the distance heuristics below.
Units must match the edge costs. If a step can cost 0.5, Manhattan distance overestimates; multiply it by the cheapest possible step cost. The maximum of several admissible heuristics is still admissible and at least as good as each.
| Movement allowed | Heuristic | Formula (dx, dy = distance to goal) |
|---|---|---|
| 4 directions, cost 1 | Manhattan | dx + dy |
| 8 directions, cost 1 | Chebyshev | max(dx, dy) |
| 8 directions, diagonal cost √2 | Octile | max(dx, dy) + (√2 − 1)·min(dx, dy) |
| Any direction | Euclidean | √(dx² + dy²) |
- Relax the problem to get an admissible h
- Scale h by the cheapest step cost
Terms, operations, and practical uses
Search scores
- g-scoreCost of the cheapest path found so far from the start to this node. Exact, not an estimate.
- Heuristic hEstimated cost from this node to the goal, for example Manhattan distance on a 4-direction grid.
- f-scoreg + h: the estimated cost of the cheapest route through this node. The open list is ordered by it.
Correctness
- Admissible heuristicNever overestimates the real remaining cost. Guarantees the path A* returns is a cheapest one.
- Consistent heuristich(u) ≤ cost(u, v) + h(v) on every edge and h(goal) = 0. Popped nodes are final and never reopened.
- ReopeningNeeded when h is admissible but not consistent: a closed node whose g improves goes back on the open list.
Implementation
- Open listMin-heap of nodes waiting to be expanded, ordered by f; may hold old entries for the same node.
- Stale entryA heap entry whose g is worse than the node's current best g. Skip it when popped.
- Parent mapFor each node, the node it was reached from on its best path. Walk it back from the goal to get the route.
Code in Python, C++ and Java
import heapq
GRID = [
"...#....",
"...#....",
"S.~~~~.G",
"........",
"........",
]
SWAMP_COST = 5
def a_star(grid, use_heuristic=True):
rows, cols = len(grid), len(grid[0])
find = lambda ch: next((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == ch)
start, goal = find("S"), find("G")
def h(cell):
if not use_heuristic:
return 0
return abs(cell[0] - goal[0]) + abs(cell[1] - goal[1])
best_g = {start: 0}
parent = {}
closed = set()
count = 0
# (f, -g, insertion order, cell): ties on f go to the larger g
open_list = [(h(start), 0, count, start)]
while open_list:
f, neg_g, _, cell = heapq.heappop(open_list)
g = -neg_g
if cell in closed or g != best_g[cell]:
continue # stale entry
closed.add(cell)
if cell == goal:
path = [cell]
while path[-1] in parent:
path.append(parent[path[-1]])
return g, len(closed), path[::-1]
r, c = cell
for nr, nc in ((r, c + 1), (r - 1, c), (r + 1, c), (r, c - 1)):
if not (0 <= nr < rows and 0 <= nc < cols) or grid[nr][nc] == "#":
continue
ng = g + (SWAMP_COST if grid[nr][nc] == "~" else 1)
if ng < best_g.get((nr, nc), float("inf")):
best_g[(nr, nc)] = ng
parent[(nr, nc)] = cell
count += 1
heapq.heappush(open_list, (ng + h((nr, nc)), -ng, count, (nr, nc)))
return None, len(closed), []
cost, expanded, path = a_star(GRID)
print("A*: cost", cost, "expanded", expanded)
print("path", " ".join(f"({c},{r})" for r, c in path))
cost, expanded, _ = a_star(GRID, use_heuristic=False)
print("Dijkstra: cost", cost, "expanded", expanded)#include <cstdlib>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
const vector<string> GRID = {
"...#....",
"...#....",
"S.~~~~.G",
"........",
"........",
};
const int SWAMP_COST = 5;
typedef pair<int, int> Cell;
struct Result {
int cost, expanded;
vector<Cell> path;
};
Result aStar(const vector<string>& grid, bool useHeuristic) {
int rows = grid.size(), cols = grid[0].size();
Cell start, goal;
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 'S') start = {r, c};
if (grid[r][c] == 'G') goal = {r, c};
}
auto h = [&](Cell cell) {
return useHeuristic ? abs(cell.first - goal.first) + abs(cell.second - goal.second) : 0;
};
map<Cell, int> bestG = {{start, 0}};
map<Cell, Cell> parent;
set<Cell> closed;
int count = 0;
// (f, -g, insertion order, row, col): ties on f go to the larger g
typedef tuple<int, int, int, int, int> Entry;
priority_queue<Entry, vector<Entry>, greater<Entry>> open;
open.push({h(start), 0, count, start.first, start.second});
while (!open.empty()) {
auto [f, negG, order, r, c] = open.top();
open.pop();
Cell cell = {r, c};
int g = -negG;
if (closed.count(cell) || g != bestG[cell]) continue; // stale entry
closed.insert(cell);
if (cell == goal) {
vector<Cell> path = {cell};
while (parent.count(path.back())) path.push_back(parent[path.back()]);
return {g, (int)closed.size(), vector<Cell>(path.rbegin(), path.rend())};
}
int moves[4][2] = {{0, 1}, {-1, 0}, {1, 0}, {0, -1}};
for (auto& m : moves) {
int nr = r + m[0], nc = c + m[1];
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || grid[nr][nc] == '#') continue;
int ng = g + (grid[nr][nc] == '~' ? SWAMP_COST : 1);
Cell next = {nr, nc};
if (!bestG.count(next) || ng < bestG[next]) {
bestG[next] = ng;
parent[next] = cell;
count++;
open.push({ng + h(next), -ng, count, nr, nc});
}
}
}
return {-1, (int)closed.size(), {}};
}
int main() {
Result a = aStar(GRID, true);
cout << "A*: cost " << a.cost << " expanded " << a.expanded << '\n';
cout << "path";
for (auto& [r, c] : a.path) cout << " (" << c << "," << r << ")";
cout << '\n';
Result d = aStar(GRID, false);
cout << "Dijkstra: cost " << d.cost << " expanded " << d.expanded << '\n';
}import java.util.*;
public class Main {
static final String[] GRID = {
"...#....",
"...#....",
"S.~~~~.G",
"........",
"........",
};
static final int SWAMP_COST = 5;
// returns {cost, expanded}; path is filled in from start to goal
static int[] aStar(String[] grid, boolean useHeuristic, List<int[]> path) {
int rows = grid.length, cols = grid[0].length();
int[] start = null, goal = null;
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) {
if (grid[r].charAt(c) == 'S') start = new int[]{r, c};
if (grid[r].charAt(c) == 'G') goal = new int[]{r, c};
}
final int[] g0 = goal;
int[][] bestG = new int[rows][cols];
for (int[] row : bestG) Arrays.fill(row, Integer.MAX_VALUE);
int[][][] parent = new int[rows][cols][];
boolean[][] closed = new boolean[rows][cols];
int expanded = 0, count = 0;
// {f, -g, insertion order, row, col}: ties on f go to the larger g
PriorityQueue<int[]> open = new PriorityQueue<>((a, b) -> {
for (int i = 0; i < 3; i++) if (a[i] != b[i]) return Integer.compare(a[i], b[i]);
return 0;
});
bestG[start[0]][start[1]] = 0;
open.add(new int[]{h(start[0], start[1], g0, useHeuristic), 0, count, start[0], start[1]});
while (!open.isEmpty()) {
int[] e = open.poll();
int r = e[3], c = e[4], g = -e[1];
if (closed[r][c] || g != bestG[r][c]) continue; // stale entry
closed[r][c] = true;
expanded++;
if (r == goal[0] && c == goal[1]) {
for (int[] cell = new int[]{r, c}; cell != null; cell = parent[cell[0]][cell[1]]) path.add(0, cell);
return new int[]{g, expanded};
}
int[][] moves = {{0, 1}, {-1, 0}, {1, 0}, {0, -1}};
for (int[] m : moves) {
int nr = r + m[0], nc = c + m[1];
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || grid[nr].charAt(nc) == '#') continue;
int ng = g + (grid[nr].charAt(nc) == '~' ? SWAMP_COST : 1);
if (ng < bestG[nr][nc]) {
bestG[nr][nc] = ng;
parent[nr][nc] = new int[]{r, c};
count++;
open.add(new int[]{ng + h(nr, nc, g0, useHeuristic), -ng, count, nr, nc});
}
}
}
return new int[]{-1, expanded};
}
static int h(int r, int c, int[] goal, boolean useHeuristic) {
return useHeuristic ? Math.abs(r - goal[0]) + Math.abs(c - goal[1]) : 0;
}
public static void main(String[] args) {
List<int[]> path = new ArrayList<>();
int[] a = aStar(GRID, true, path);
System.out.println("A*: cost " + a[0] + " expanded " + a[1]);
StringBuilder sb = new StringBuilder("path");
for (int[] cell : path) sb.append(" (").append(cell[1]).append(",").append(cell[0]).append(")");
System.out.println(sb);
int[] d = aStar(GRID, false, new ArrayList<>());
System.out.println("Dijkstra: cost " + d[0] + " expanded " + d[1]);
}
}Step through it
Running on 8 x 5 grid, S (0, 2), G (7, 2), swamp cost 5, Manhattan h
A* vs Dijkstra and Greedy Best-First
A* sits between two other searches. With h = 0 it is exactly Dijkstra's algorithm: the order depends on g alone, so it spreads out evenly in every direction. On the tracer's grid it finds the same cost 9 but expands 27 cells instead of 12.
With the priority h alone it is greedy best-first search. It rushes at the goal and often expands very little, but it ignores what it has already paid: on the tracer's grid it walks straight through the swamp for a cost of 23.
So for A* vs Dijkstra, the answer is the same and the work differs. Dijkstra is the right choice when you need distances to every node or have no useful estimate; A* is for one goal with a good heuristic. On an unweighted graph with h = 0, A* explores in the same order as breadth-first search.
| Priority | Optimal? | Explores | |
|---|---|---|---|
| Dijkstra | g | Yes | Everything cheaper than the goal |
| A* | g + h | Yes, with admissible h | Mostly toward the goal |
| Greedy best-first | h | No | Least, but can take bad routes |
| Weighted A* | g + w·h, w > 1 | Within a factor w | Less than A* |
- Same answer as Dijkstra; fewer expansions with a good h
- Weighted A* trades a bounded loss in cost for speed
Cost, Memory and A* in AI
With a binary heap A* is O((V + E) log V) in the worst case, the same as Dijkstra: a useless heuristic gives no saving. Its gain is in practice, through fewer expansions. Memory is often the real limit, since the open and closed sets can hold a large part of the graph.
Edge cases to test: start equal to goal (cost 0), an unreachable goal (the open list runs dry after every reachable node), ties in f (breaking them toward larger g reduces wasted work), stale heap entries (skip an entry whose g is no longer the best), and negative edge costs, which A* does not support.
In AI courses, the A star algorithm is the standard example of informed search: route planning in games and maps, robot motion, and puzzles such as the 8-puzzle with the sum of tile distances as h. When memory runs out, IDA* repeats depth-first searches with a rising f limit, using memory proportional to the path length.
- Worst case equals Dijkstra; the win is fewer expansions
- Memory, not time, is usually what runs out
- IDA* trades repeated work for tiny memory