A* Pathfinding visualization

Best-first search on a grid using cost-so-far g plus a heuristic h towards the goal.

A* always expands the open cell with the lowest f = g + h, where g is the steps taken and h is the Manhattan distance to the goal. A good heuristic focuses the search toward the target.

With an admissible heuristic (never overestimates) the first time the goal is expanded its path is optimal. If the open set empties first, no path exists.

Complexity

Time: best O(d), average O(E log V), worst O(E log V). Space: O(V). Difficulty: Advanced.

Pseudocode

procedure aStar(grid, S, G):
  open ← {S}; g[S] ← 0; f[S] ← h(S)
  while open not empty:
    cur ← cell in open with lowest f
    if cur = G: reconstruct path; return
    move cur from open to closed
    for each 4-way neighbour n that is not a wall:
      if g[cur] + 1 < g[n]:
        parent[n] ← cur; g[n] ← g[cur] + 1; f[n] ← g[n] + h(n); open.add(n)
  return "no path"

More graphs algorithms