A* Search Algorithm
A* Search Algorithm
A* (pronounced "A-star") improves on Dijkstra by using a heuristic — an estimate of the remaining cost to the goal. This guides the search toward the goal, exploring fewer nodes while still guaranteeing the cheapest path.
The Formula
A* evaluates each node using:
f(node) = g(node) + h(node)
- g(node) = actual cost from start to this node (same as Dijkstra tracks)
- h(node) = estimated cost from this node to the goal (the heuristic)
- f(node) = total estimated cost of the best path through this node
The priority queue orders by f(node) instead of just g(node).
Code Snippet
Uses the WeightedGraph class from the Graphs and Weighted Graphs article:
def astar_search(graph, start_node: int, goal_node: int, heuristic) -> tuple[list[int], int]:
"""Find cheapest path using actual cost + heuristic estimate.
heuristic(node, goal) must never overestimate true cost."""
num_nodes = graph.num_nodes
cost_to_reach = [float('inf')] * num_nodes
parent_of = [-1] * num_nodes
visited = [False] * num_nodes
cost_to_reach[start_node] = 0
estimated_total = heuristic(start_node, goal_node)
frontier = [(estimated_total, start_node)] # (f_score, node)
while frontier:
frontier.sort()
current_f_score, current_node = frontier.pop(0)
if visited[current_node]:
continue
visited[current_node] = True
if current_node == goal_node:
break
for neighbor_node, edge_weight in graph.get_neighbors(current_node):
if visited[neighbor_node]:
continue
new_cost = cost_to_reach[current_node] + edge_weight
if new_cost < cost_to_reach[neighbor_node]:
cost_to_reach[neighbor_node] = new_cost
parent_of[neighbor_node] = current_node
f_score = new_cost + heuristic(neighbor_node, goal_node)
frontier.append((f_score, neighbor_node))
# Reconstruct path
path = []
node = goal_node
while node != -1:
path.append(node)
node = parent_of[node]
path.reverse()
total_cost = cost_to_reach[goal_node]
return path, total_cost
def manhattan_distance(node_a: int, node_b: int, grid_columns: int) -> int:
"""Admissible heuristic for grid-based movement (no diagonal moves)."""
row_a, col_a = node_a // grid_columns, node_a % grid_columns
row_b, col_b = node_b // grid_columns, node_b % grid_columns
return abs(row_a - row_b) + abs(col_a - col_b)
Admissibility: The Key Requirement
A heuristic is admissible if it never overestimates the true remaining cost. When admissible, A* guarantees the optimal (cheapest) path.
Common admissible heuristics for grids:
- Manhattan distance: for 4-directional movement (no diagonals)
- Euclidean distance: for any-direction movement
- Zero: always admissible, but makes A* behave like Dijkstra (no guidance)
If the heuristic overestimates, A* may find a suboptimal path but runs faster — this trade-off is sometimes acceptable.
A* vs Dijkstra
| Property | Dijkstra | A* |
|---|---|---|
| Expansion order | By g(node) only | By g(node) + h(node) |
| Nodes explored | More (explores all directions) | Fewer (guided toward goal) |
| Optimal path | Yes | Yes (if heuristic is admissible) |
| Requires | Non-negative weights | Non-negative weights + heuristic |
| Best for | Unknown goal position | Known goal position |
The Visual Difference
On a weighted maze:
- Dijkstra expands in concentric cost-circles outward from the start
- A* expands preferentially toward the goal, skipping expensive dead ends
Both find the same cheapest path. A* just explores fewer cells to get there.
When to Use A*
- Pathfinding in games (grid-based movement, known target position)
- Robot navigation (known map, known destination)
- Any weighted shortest-path problem where you have a good heuristic for remaining cost
- When Dijkstra is too slow because it explores too many irrelevant nodes