The A* (A-Star) Algorithm
Why A*?
Moving straight towards a target is easy. Moving around walls? Not so much.
A* is the industry standard because it's both fast (like Greedy Best-First) and accurate (like Dijkstra). It finds the shortest path while intelligently guessing which direction is promising.
Interactive A* Solver
Click to place walls. Drag the Green (Start) or Red (End) points. The algorithm updates instantly.
How It Works (The Math)
A* analyzes cells (nodes) using three values:
- G Cost: Distance from Start Node to current node.
- H Cost (Heuristic): Estimated distance from current node to End Node (ignoring walls).
- F Cost: G + H. The algorithm always explores the node with the lowest F cost first.
function findPath(start, end) {
let openSet = [start];
let closedSet = [];
while (openSet.length > 0) {
// 1. Get node with lowest F cost
let current = getLowestFCost(openSet);
if (current === end) {
return retracePath(start, end);
}
openSet.remove(current);
closedSet.push(current);
// 2. Check neighbors
for (let neighbor of current.neighbors) {
if (closedSet.includes(neighbor) || !neighbor.walkable) {
continue;
}
let newCostToNeighbor = current.gCost + getDistance(current, neighbor);
if (newCostToNeighbor < neighbor.gCost || !openSet.includes(neighbor)) {
neighbor.gCost = newCostToNeighbor;
neighbor.hCost = getDistance(neighbor, end);
neighbor.parent = current;
if (!openSet.includes(neighbor)) {
openSet.push(neighbor);
}
}
}
}
}
Before you continue
Direct answer: A* searches through possible routes by combining the cost already spent with a heuristic estimate of the remaining distance.
What you need first
Arrays, objects, and grid coordinates.
After this lesson
You can explain the idea, change the supplied example, and choose the next related lesson.
When to use it
Use A* for a grid where an enemy needs a route. Do not run a full search every frame for every enemy.
Common mistake
Using a heuristic that overestimates distance when you need the shortest path.
Try it and check it
This lesson includes its runnable example or code experiment above. Change one value, run it again, and confirm the visible result changes before moving on.
Real game connection
Pair this with finite state machines for enemy decisions.
Compatibility: Test in a current Chrome, Firefox, Safari, or Edge browser. Canvas and standard input work broadly in current browsers; audio still needs a user action.
Source and update
Reviewed against MDN Web Docs. Updated 2026-07-14. This page does not claim performance results beyond the local example check.