algosgraphs

a*

dijkstra with a sense of direction: a guess of the distance left pulls the search toward the goal.

report a mistake
.md

every cell found so far waits in a heap by f = g + h. g is the cost of the best way to it, h a guess of the cost left. the smallest f comes off first, so the search heads for the goal and only spreads out when it's blocked.

finds
a shortest path when h never guesses more than the real cost
expands
fewer cells 20 of 44 on the page's grid. h = 0 takes 41
per cell
O(log n) the heap. bfs pays O(1), so a* wins by touching fewer cells
needs
a safe guess an overestimate can send it the long way round
space
O(n) g, parent and done for every cell found, and the heap
reach for it
  • routes on a map, with the straight-line distance as the guess
  • a path through a grid or a maze in a game
  • puzzles with a cheap lower bound, like sliding tiles with the tiles' manhattan distances
  • planning, where a state's cost to go has a known floor
  • any shortest path with one goal and a guess that never overestimates
on this page
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. the guess, up close
  6. complexity
  7. implementations
  8. pitfalls
  9. variants
  10. practice
  11. how real libraries do it
  12. sources

a* is dijkstra with a sense of direction. dijkstra settles the closest cell next, so on a grid it spreads out evenly, like bfs. a* adds a guess of the distance still to go, h, and takes the cell with the smallest g + h next: the one that looks like it’s on the shortest way through. on a grid with four moves the guess is the manhattan distance, which can’t be too big, so when the goal comes off the heap the way to it is a shortest one. hart, nilsson and raphael described the algorithm in 1968, and proved that no search that is sure to find a shortest path and knows no more than the guess does can expand fewer cells, ties aside.1

the idea

a grid of 8 by 6. the start is (2, 0), the goal (2, 7), and a wall runs down column 4 from the top edge to row 3. every open cell has a guess of the distance left, h: rows apart plus columns apart. the start’s is 7, and it waits alone on the heap with f = 0 + 7.

an animation in six steps on a grid of 8 columns by 6 rows. the start, at row 2 column 0, is cyan, the goal, at row 2 column 7, is amber, and a wall fills column 4 from the top row down to row 3. a readout shows g, h and f for the cell being expanded and a count of cells expanded. each cell found gets a ring with its f written in it, the cell coming off the heap turns white, then settles to a quiet fill. first the start: g 0, h 7, f 7. then the search runs right along row 2, f 7 each time, to the cell before the wall at column 3. then the band of f 9 fills in: the cells above and below the row out to the wall, tried closer to the goal first, 8 of them, none leading on. then f 11: a dead end at the top, then the cells under the wall, and from row 4 column 4 on each pop is one step closer to the goal. last the goal pops with f 11 and the path draws in white: 11 steps around the bottom of the wall, 20 cells expanded of 44. the caption adds that the same search with h = 0, dijkstra, expands 41, and so does bfs.

watch it run

step through the same grid, and change it: tap a cell to make it a wall or open it again. each found cell shows its f and an arrow back to the cell it was found from, its parent. the strip under the grid is the heap, each entry as f · h, in the order they’d come off: the first one is next. the pseudocode follows along. open a gap in the wall at (1, 4) and the search goes straight through it: 10 cells for 9 steps, where h = 0 expands 40.

walls
7

tap a cell to make it a wall or open it again. the start and goal stay open.

7·7

the start, (2, 0): g 0, and h 7 to the goal, so f 7. it's the only entry on the heap

expanded
0
pushed
1
waiting
1
step
1 of 86
pseudocode
a_star(grid, start, goal):  g = {start: 0}  # the cost of the best way found to each cell  parent = {}  closed = set()  # expanded: their g is final  heap = [(h(start), h(start), start)]  # entries (f, h, cell): the smallest f pops, then the smallest h  while heap:    f, _, c = pop(heap)    if c in closed: continue  # a stale entry: c was found cheaper after it went in    closed.add(c)    if c == goal: return path(parent, start, goal)    for nb in neighbors(c):  # up, left, right, down. walls are not neighbors      if nb in closed: continue      if nb not in g or g[c] + 1 < g[nb]:        g[nb] = g[c] + 1        parent[nb] = c        push(heap, (g[nb] + h(nb), h(nb), nb))  return []  # the heap ran dry: no way to the goal h(c):  # the manhattan distance to the goal: never more than the real cost with these moves  return |row(c) - row(goal)| + |col(c) - col(goal)|

an interactive stepper on the grid of 8 by 6 from the animation, with its walls, start and goal. tap a cell to make it a wall or open it again; the start and goal stay open, and the stepper jumps to the end of the new run. each found cell shows its f and a small arrow toward its parent. under the grid a strip shows the heap's entries in the order they'd come off, each as f · h, the first one ringed in cyan, and counters of cells expanded, entries pushed and entries waiting. each step is one line of the pseudocode: a cell coming off the heap in white, a neighbor found, found cheaper, skipped as done or left as it was, with a short white line to the neighbor being looked at, or a stale entry skipped. done cells go quiet, and at the end the path lights up with a white line along it. buttons bring back the page's grid or make random walls.

try it

the whole search hangs on one comparison: the smallest f, then the smallest h. make the calls.

1 cell expanded so far. which cell comes off the heap next? tap it.

9779

tap a cell.

0 / 0 right

a practice exercise with four kinds of question. some show the grid mid-run, with the f of every found cell and the done cells quiet, and ask you to tap the cell that comes off the heap next, ties on f included, which the smaller h breaks, and then the lower cell number. some name a found cell and its g and ask for its f, with the traps as choices: g alone, h alone, and a diagonal's worth of h. some give a cell on an open grid, the real cost to the goal and a rule for guessing it, and ask whether the rule is safe for a*. the rest ask how many cells a* expands between two cells of an open grid, where the steps alone, the rectangle between them and the whole grid are the traps. once a count is answered, the grid shows the cells a* expanded and its path.

pseudocode

pseudocode
a_star(grid, start, goal):
  g = {start: 0}  # the cost of the best way found to each cell
  parent = {}
  closed = set()  # expanded: their g is final
  heap = [(h(start), h(start), start)]  # entries (f, h, cell): the smallest f pops, then the smallest h
  while heap:
    f, _, c = pop(heap)
    if c in closed: continue  # a stale entry: c was found cheaper after it went in
    closed.add(c)
    if c == goal: return path(parent, start, goal)
    for nb in neighbors(c):  # up, left, right, down. walls are not neighbors
      if nb in closed: continue
      if nb not in g or g[c] + 1 < g[nb]:
        g[nb] = g[c] + 1
        parent[nb] = c
        push(heap, (g[nb] + h(nb), h(nb), nb))
  return []  # the heap ran dry: no way to the goal

h(c):  # the manhattan distance to the goal: never more than the real cost with these moves
  return |row(c) - row(goal)| + |col(c) - col(goal)|

the heap holds (f, h, cell), compared in that order: the smallest f, then the smallest h, closer to the goal first, then the lower cell number. no two entries are the same, so every run pops in one order, in every language on this page. a cell can be on the heap twice, when a cheaper way to it turns up after its first entry went in. the line after the pop skips the stale one.

the guess, up close

h = 0, dijkstra

expanded
17
path
7 steps

h = manhattan

expanded
12
path
7 steps

h = 2 × manhattan

expanded
10
path
9 steps, not 7
  • expanded
  • on the path it returns
  • a wall

three copies of a grid of 6 columns by 3 rows, with the start at row 2 column 0, the goal at row 0 column 5, and one wall at row 0 column 4. each copy runs the search with a different guess, shades the cells it expanded, lights up the path it returns with a white line along it, and counts under it. with h = 0, dijkstra: 17 cells expanded, every open one, and a path of 7 steps that runs along the middle row. with h the manhattan distance: 12 cells, the middle row, the top row up to the wall and the two ends, and the same 7-step path. with h doubled: 10 cells, but the search climbs to the top row, runs into the wall, and the path it returns goes around it: 9 steps, not 7. a legend names the shades.

complexity

a*h = 0bfs
per cellO(log n)O(log n)O(1)
worstO(n log n)O(n log n)O(n)
spaceO(n)O(n)O(n)

per cell is the heap’s pops and pushes for a* and h = 0, and the queue’s for bfs. where they differ is how many cells they expand: a* takes every cell whose f is under the goal’s, plus some of the ties, and h = 0 and bfs take every cell nearer than the goal, plus ties.

on a grid of n cells each cell has at most 4 neighbors, so the heap sees at most a few entries per cell, and the whole search is O(n log n) when the guess doesn’t help at all: a goal walled off, or h = 0. the bound is the same as dijkstra’s, and bfs beats both on paper. a* wins by what it doesn’t touch, and that depends on the guess and the walls.

01k2k3k162564096
a*
736 cells expanded
h = 0
2,555 cells expanded
bfs
2,554 cells expanded

a line chart of cells expanded against the cells in the grid, from 16 to 4,096 on a doubling scale, for square grids with a third of their cells walls, searched from one corner to the other and averaged over 100 seeded grids at each size. a*, solid cyan, stays lowest: 7.47 cells at 16 and 736 at 4,096. the same search with h = 0, dashed amber, and bfs, dotted, lie on top of each other: 11.5 at 16, and 2,555 and 2,554 at 4,096. a slider picks a size and reads off all three.

on 64 by 64 grids with a third of the cells walls, corner to corner, a* expanded 736 cells on average, the same search with h = 0 2,555, and bfs 2,554: under a third. on 4 by 4 grids there’s nowhere to save, 7.5 cells against 11.5. the share of the grid a* touches falls as the grid grows, from 47% of the cells at 4 by 4 to 18% at 64 by 64, while h = 0 stays between 60% and 72% whatever the size: every cell nearer than the far corner. h = 0 and bfs differ only at the goal’s own distance, where the heap takes the lower cell number and the queue takes the earlier find.

implementations

each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including the page’s grid, an open grid where every pop is one step closer to the goal, and 2000 seeded grids of up to 10 by 10 with about a third walls against a bfs. every tab orders its heap the same way, f, then h, then the cell, so the paths and the counts match across languages. a start or goal on a wall, a width that doesn’t divide the cells, and a cell outside the grid are turned away: typescript throws a RangeError, python raises a ValueError for a bad grid or a wall and an IndexError for a cell outside it, go and rust panic, swift stops on a precondition, and c returns false with nothing left allocated.

go/algos/astar/astar.go
// Package astar is a reference a* on a grid: dijkstra with a sense of direction. cells are numbered row by
// row, a wall is a cell you can't stand on, and a move goes up, left, right or down for a cost of 1. every
// cell found so far waits in a min-heap by f = g + h: g is the cost of the best way to it so far, and h is
// a guess of the cost left, the manhattan distance to the goal. on this grid h never guesses more than the
// real cost, so when the goal comes off the heap the way to it is a shortest one. cells that can't be on a
// short way have a big f and wait, which is what the same search with h = 0, dijkstra, can't do.
package astar

import (
	"fmt"
	"slices"
)

// entry is a heap entry: f, then h (closer to the goal first), then the cell. Every run pops in one order.
type entry struct{ f, h, cell int }

// less reports whether a comes off the heap before b. No two entries are the same, so one always does.
func less(a, b entry) bool {
	if a.f != b.f {
		return a.f < b.f
	}
	if a.h != b.h {
		return a.h < b.h
	}
	return a.cell < b.cell
}

// minHeap is a binary min-heap of entries in a slice: entry i's children are at 2i + 1 and 2i + 2.
type minHeap []entry

// push adds e at the end, then swaps it up while it comes before its parent.
func (h *minHeap) push(e entry) {
	*h = append(*h, e)
	s := *h
	for i := len(s) - 1; i > 0; {
		parent := (i - 1) / 2
		if !less(s[i], s[parent]) {
			return
		}
		s[i], s[parent] = s[parent], s[i]
		i = parent
	}
}

// pop takes out the first entry. The last one moves to the top and swaps down past children before it.
func (h *minHeap) pop() entry {
	s := *h
	top := s[0]
	last := len(s) - 1
	s[0] = s[last]
	s = s[:last]
	*h = s
	for i := 0; ; {
		left, right := 2*i+1, 2*i+2
		first := i
		if left < len(s) && less(s[left], s[first]) {
			first = left
		}
		if right < len(s) && less(s[right], s[first]) {
			first = right
		}
		if first == i {
			return top
		}
		s[i], s[first] = s[first], s[i]
		i = first
	}
}

// Search returns the shortest path from start to goal, as cells from start to goal, and how many cells the
// search expanded: took off the heap and settled, the goal included. walls[c] is true for a wall; the grid
// has width columns and len(walls) / width rows. The path is empty when the goal can't be reached, after
// every cell it can reach is expanded, and just the start when the start is the goal. A size that isn't
// whole rows and a start or goal on a wall panic, and so does a cell outside the grid.
func Search(walls []bool, width, start, goal int) (path []int, expanded int) {
	n := len(walls)
	if width < 1 || n%width != 0 {
		panic(fmt.Sprintf("astar: no grid of %d cells with %d columns", n, width))
	}
	for _, c := range []int{start, goal} {
		if walls[c] { // a cell outside the grid panics here, as an index out of range
			panic(fmt.Sprintf("astar: cell %d is a wall", c))
		}
	}
	row := func(c int) int { return c / width }
	col := func(c int) int { return c % width }
	// the manhattan distance to the goal: with these four moves, no way there takes fewer steps
	h := func(c int) int {
		dr, dc := row(c)-row(goal), col(c)-col(goal)
		return max(dr, -dr) + max(dc, -dc)
	}
	// the cells next to c inside the grid, in the order up, left, right, down
	neighbors := func(c int) []int {
		var out []int
		if c >= width {
			out = append(out, c-width)
		}
		if col(c) > 0 {
			out = append(out, c-1)
		}
		if col(c) < width-1 {
			out = append(out, c+1)
		}
		if c+width < n {
			out = append(out, c+width)
		}
		return out
	}

	g := make([]int, n)
	parent := make([]int, n)
	for c := range n {
		g[c], parent[c] = -1, -1 // -1: not found yet
	}
	closed := make([]bool, n)
	var heap minHeap
	g[start] = 0
	heap.push(entry{h(start), h(start), start})
	for len(heap) > 0 {
		c := heap.pop().cell
		if closed[c] {
			continue // a stale entry: c was found cheaper after this one went in, and is done already
		}
		closed[c] = true
		expanded++
		if c == goal {
			break
		}
		for _, nb := range neighbors(c) {
			if walls[nb] || closed[nb] {
				continue
			}
			if g[nb] == -1 || g[c]+1 < g[nb] {
				g[nb] = g[c] + 1
				parent[nb] = c
				heap.push(entry{g[nb] + h(nb), h(nb), nb})
			}
		}
	}
	if !closed[goal] {
		return nil, expanded
	}
	for c := goal; c != -1; c = parent[c] {
		path = append(path, c)
	}
	slices.Reverse(path)
	return path, expanded
}
rust/algos/src/a_star.rs
//! a* on a grid: dijkstra with a sense of direction. cells are numbered row by row, a wall is a cell you can't stand on, and a move goes up, left, right or down for a cost of 1. every cell found so far waits in a min-heap by f = g + h: g is the cost of the best way to it so far, and h is a guess of the cost left, here the manhattan distance to the goal. on this grid h never guesses more than the real cost, so when the goal comes off the heap the way to it is a shortest one. cells that can't be on a short way have a big f and wait, which is what the same search with h = 0, dijkstra, can't do.

/// What the search found: the path from start to goal, as cells, and how many cells it expanded.
#[derive(Debug, PartialEq)]
pub struct Found {
    pub path: Vec<usize>,
    pub expanded: usize,
}

/// A heap entry: f first, then h (closer to the goal first), then the cell. Tuples compare field
/// by field, so every run pops in one order.
type Entry = (usize, usize, usize);

/// Adds `e` at the end, then swaps it up while it comes before its parent.
fn push(heap: &mut Vec<Entry>, e: Entry) {
    heap.push(e);
    let mut i = heap.len() - 1;
    while i > 0 {
        let parent = (i - 1) / 2;
        if heap[parent] <= heap[i] {
            return;
        }
        heap.swap(parent, i);
        i = parent;
    }
}

/// Takes out the first entry: the last one moves to the top and swaps down past children that
/// come before it. `None` when the heap is empty.
fn pop(heap: &mut Vec<Entry>) -> Option<Entry> {
    if heap.is_empty() {
        return None;
    }
    let top = heap.swap_remove(0); // the last entry fills slot 0
    let mut i = 0;
    loop {
        let mut first = i;
        for c in [2 * i + 1, 2 * i + 2] {
            if c < heap.len() && heap[c] < heap[first] {
                first = c;
            }
        }
        if first == i {
            return Some(top);
        }
        heap.swap(i, first);
        i = first;
    }
}

/// The shortest path from `start` to `goal`, as cells from start to goal, and how many cells the
/// search expanded: took off the heap and settled, the goal included. `walls[c]` is true for a
/// wall; the grid has `width` columns and `walls.len() / width` rows. The path is empty when the
/// goal can't be reached, after every cell it can reach is expanded, and just the start when the
/// start is the goal. A size that isn't whole rows, a cell outside the grid, and a start or goal
/// on a wall panic.
pub fn a_star(walls: &[bool], width: usize, start: usize, goal: usize) -> Found {
    let n = walls.len();
    assert!(
        width > 0 && n.is_multiple_of(width),
        "no grid of {n} cells with {width} columns"
    );
    for c in [start, goal] {
        // a cell outside the grid panics here first, as any index out of range does
        assert!(!walls[c], "cell {c} is a wall");
    }
    let row = |c: usize| c / width;
    let col = |c: usize| c % width;
    // the manhattan distance to the goal: with these four moves, no way there takes fewer steps
    let h = |c: usize| row(c).abs_diff(row(goal)) + col(c).abs_diff(col(goal));
    // the cells next to c inside the grid, in the order up, left, right, down
    let neighbors = |c: usize| {
        let mut out = Vec::with_capacity(4);
        if c >= width {
            out.push(c - width);
        }
        if col(c) > 0 {
            out.push(c - 1);
        }
        if col(c) < width - 1 {
            out.push(c + 1);
        }
        if c + width < n {
            out.push(c + width);
        }
        out
    };

    let mut g = vec![None; n]; // None: not found yet
    let mut parent = vec![None; n];
    let mut closed = vec![false; n];
    let mut heap = Vec::new();
    let mut expanded = 0;
    g[start] = Some(0);
    push(&mut heap, (h(start), h(start), start));
    while let Some((_, _, c)) = pop(&mut heap) {
        if closed[c] {
            // a stale entry: c was found cheaper after this one went in, and is done already
            continue;
        }
        closed[c] = true;
        expanded += 1;
        if c == goal {
            break;
        }
        let gc = g[c].expect("a cell on the heap has its g");
        for nb in neighbors(c) {
            if walls[nb] || closed[nb] {
                continue;
            }
            if g[nb].is_none_or(|gn| gc + 1 < gn) {
                g[nb] = Some(gc + 1);
                parent[nb] = Some(c);
                push(&mut heap, (gc + 1 + h(nb), h(nb), nb));
            }
        }
    }
    if !closed[goal] {
        return Found {
            path: Vec::new(),
            expanded,
        };
    }
    let mut path = Vec::new();
    let mut at = Some(goal);
    while let Some(c) = at {
        path.push(c);
        at = parent[c];
    }
    path.reverse();
    Found { path, expanded }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// xorshift32 seeded with `seed`, like the other tests here: each call gives the next number.
    fn xorshift32(seed: u32) -> impl FnMut() -> usize {
        let mut state = seed;
        move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        }
    }

    /// A grid drawn as rows of text, split at whitespace: `#` a wall, `.` open, `s` the start, `g`
    /// the goal. Cells are numbered row by row. Gives the walls, the width, the start and the goal.
    fn grid(picture: &str) -> (Vec<bool>, usize, usize, usize) {
        let rows: Vec<&str> = picture.split_whitespace().collect();
        let cells: Vec<char> = rows.concat().chars().collect();
        let at = |mark| cells.iter().position(|&ch| ch == mark).expect("a mark");
        let walls = cells.iter().map(|&ch| ch == '#').collect();
        (walls, rows[0].len(), at('s'), at('g'))
    }

    /// The cells next to `c` inside the grid: up, left, right, down.
    fn neighbors(c: usize, width: usize, n: usize) -> Vec<usize> {
        let col = c % width;
        let mut out = Vec::new();
        if c >= width {
            out.push(c - width);
        }
        if col > 0 {
            out.push(c - 1);
        }
        if col < width - 1 {
            out.push(c + 1);
        }
        if c + width < n {
            out.push(c + width);
        }
        out
    }

    /// Steps from `start` to every cell by a bfs over the open cells: `None` where there's no way.
    fn bfs(walls: &[bool], width: usize, start: usize) -> Vec<Option<usize>> {
        let mut dist = vec![None; walls.len()];
        dist[start] = Some(0);
        let mut queue = vec![start];
        let mut i = 0;
        while i < queue.len() {
            let c = queue[i];
            i += 1;
            for nb in neighbors(c, width, walls.len()) {
                if !walls[nb] && dist[nb].is_none() {
                    dist[nb] = dist[c].map(|d| d + 1);
                    queue.push(nb);
                }
            }
        }
        dist
    }

    /// How many cells the start can reach, the start included.
    fn reachable(walls: &[bool], width: usize, start: usize) -> usize {
        bfs(walls, width, start).iter().flatten().count()
    }

    /// Whether `path` walks from `start` to `goal` one step at a time over open cells.
    fn valid(path: &[usize], walls: &[bool], width: usize, start: usize, goal: usize) -> bool {
        path.first() == Some(&start)
            && path.last() == Some(&goal)
            && path.iter().all(|&c| !walls[c])
            && path
                .windows(2)
                .all(|step| neighbors(step[0], width, walls.len()).contains(&step[1]))
    }

    /// Whether the search panics on these arguments.
    fn panics(walls: &[bool], width: usize, start: usize, goal: usize) -> bool {
        std::panic::catch_unwind(|| a_star(walls, width, start, goal)).is_err()
    }

    // the page's grid: 8 by 6, with a wall from the top edge down to the row below the start's, so
    // the way around is under it
    const PAGE: &str = "
        ....#...
        ....#...
        s...#..g
        ....#...
        ........
        ........";

    #[test]
    fn the_pages_grid_11_steps_around_the_wall_20_cells_expanded_of_44() {
        let (walls, width, start, goal) = grid(PAGE);
        let open = walls.iter().filter(|&&w| !w).count();
        assert_eq!((start, goal, open), (16, 23, 44));
        assert_eq!(
            a_star(&walls, width, start, goal),
            Found {
                path: vec![16, 17, 18, 19, 27, 35, 36, 37, 29, 21, 22, 23],
                expanded: 20,
            }
        );
    }

    #[test]
    fn start_is_the_goal_a_path_of_one_cell_and_one_cell_expanded() {
        let (walls, width, start, _) = grid(PAGE);
        assert_eq!(
            a_star(&walls, width, start, start),
            Found {
                path: vec![16],
                expanded: 1,
            }
        );
    }

    #[test]
    fn a_goal_behind_walls_no_path_after_every_cell_the_start_can_reach_is_expanded() {
        let ring = "
            s....
            .###.
            .#g#.
            .###.";
        let (walls, width, start, goal) = grid(ring);
        assert_eq!(
            a_star(&walls, width, start, goal),
            Found {
                path: vec![],
                expanded: 11,
            }
        );
        assert_eq!(reachable(&walls, width, start), 11);
    }

    #[test]
    fn an_open_grid_as_many_steps_as_the_manhattan_distance_and_one_cell_expanded_per_step_plus_the_start()
     {
        let width = 8;
        let walls = [false; 48];
        let manhattan =
            |a: usize, b: usize| (a / width).abs_diff(b / width) + (a % width).abs_diff(b % width);
        for (start, goal) in [(16, 23), (0, 47), (47, 0), (40, 7), (5, 42), (21, 26)] {
            let Found { path, expanded } = a_star(&walls, width, start, goal);
            let steps = manhattan(start, goal);
            assert_eq!((path.len(), expanded), (steps + 1, steps + 1));
            assert!(valid(&path, &walls, width, start, goal));
        }
        // the tie rule picks one line through the cells with equal f: the closer cell first, then
        // the lower number
        assert_eq!(
            a_star(&walls, width, 0, 47).path,
            [0, 1, 2, 3, 4, 5, 6, 7, 15, 23, 31, 39, 47]
        );
        assert_eq!(
            a_star(&walls, width, 47, 0).path,
            [47, 39, 31, 23, 15, 7, 6, 5, 4, 3, 2, 1, 0]
        );
    }

    #[test]
    fn as_short_as_a_bfs_and_a_real_path_over_open_cells_on_2000_seeded_grids() {
        let mut next = xorshift32(42);
        let mut reached = 0;
        for _ in 0..2000 {
            let width = 1 + next() % 10;
            let rows = 1 + next() % 10;
            // about a third of the cells are walls
            let walls: Vec<bool> = (0..width * rows)
                .map(|_| next().is_multiple_of(3))
                .collect();
            let open: Vec<usize> = (0..walls.len()).filter(|&c| !walls[c]).collect();
            if open.is_empty() {
                continue;
            }
            let start = open[next() % open.len()];
            let goal = open[next() % open.len()];
            let Found { path, expanded } = a_star(&walls, width, start, goal);
            match bfs(&walls, width, start)[goal] {
                None => {
                    assert_eq!(path, []);
                    assert_eq!(expanded, reachable(&walls, width, start));
                }
                Some(steps) => {
                    reached += 1;
                    assert_eq!(path.len(), steps + 1);
                    assert!(valid(&path, &walls, width, start, goal));
                    assert!(expanded >= path.len());
                    assert!(expanded <= open.len());
                }
            }
        }
        assert!(reached > 1000);
    }

    #[test]
    fn a_start_or_goal_on_a_wall_a_width_that_does_not_divide_the_cells_and_a_cell_outside_the_grid_panic()
     {
        let (walls, width, start, goal) = grid(PAGE);
        assert!(panics(&walls, width, 4, goal));
        assert!(panics(&walls, width, start, 12));
        assert!(panics(&walls, 7, start, goal));
        assert!(panics(&walls, 0, start, goal));
        // a usize can't be -1, so past the end is the only cell outside the grid there is
        assert!(panics(&walls, width, start, 48));
        assert!(panics(&[], 1, 0, 0));
    }
}
site/src/visuals/a-star/a-star.ts
/**
 * A* on a grid: dijkstra with a sense of direction. Cells are numbered row by row, a wall is a cell you can't
 * stand on, and a move goes up, left, right or down for a cost of 1. Every cell found so far waits in a min-heap
 * by f = g + h: g is the cost of the best way to it so far, and h is a guess of the cost left, here the manhattan
 * distance to the goal. On this grid h never guesses more than the real cost, so when the goal comes off the heap
 * the way to it is a shortest one. Cells that can't be on a short way have a big f and wait, which is what the
 * same search with h = 0, dijkstra, can't do.
 */

/** A heap entry: f first, then h (closer to the goal first), then the cell. Every run pops in one order. */
type Entry = [f: number, h: number, cell: number];

/** Whether a comes off the heap before b. No two entries are the same, so one of them always does. */
function less(a: Entry, b: Entry): boolean {
  for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i];
  return false;
}

/** Add e at the end, then swap it up while it comes before its parent. */
function push(heap: Entry[], e: Entry): void {
  heap.push(e);
  let i = heap.length - 1;
  while (i > 0) {
    const parent = Math.floor((i - 1) / 2);
    if (!less(heap[i], heap[parent])) return;
    [heap[parent], heap[i]] = [heap[i], heap[parent]];
    i = parent;
  }
}

/** Take out the first entry: the last one moves to the top and swaps down past children that come before it. */
function pop(heap: Entry[]): Entry {
  const top = heap[0];
  const last = heap.pop()!;
  if (heap.length > 0) {
    heap[0] = last;
    let i = 0;
    for (;;) {
      let first = i;
      for (const c of [2 * i + 1, 2 * i + 2]) if (c < heap.length && less(heap[c], heap[first])) first = c;
      if (first === i) break;
      [heap[i], heap[first]] = [heap[first], heap[i]];
      i = first;
    }
  }
  return top;
}

/**
 * The shortest path from start to goal, as cells from start to goal, and how many cells the search expanded:
 * took off the heap and settled, the goal included. walls[c] is true for a wall; the grid has width columns and
 * walls.length / width rows. The path is [] when the goal can't be reached, after every cell it can reach is
 * expanded, and [start] when the start is the goal. A size that isn't whole rows, a cell outside the grid, and a
 * start or goal on a wall are a RangeError.
 */
export function aStar(
  walls: readonly boolean[],
  width: number,
  start: number,
  goal: number,
): { path: number[]; expanded: number } {
  const n = walls.length;
  if (!Number.isInteger(width) || width < 1 || n % width !== 0)
    throw new RangeError(`no grid of ${n} cells with ${width} columns`);
  for (const c of [start, goal]) {
    if (!Number.isInteger(c) || c < 0 || c >= n) throw new RangeError(`no cell ${c}`);
    if (walls[c]) throw new RangeError(`cell ${c} is a wall`);
  }
  const row = (c: number) => Math.floor(c / width);
  const col = (c: number) => c % width;
  // the manhattan distance to the goal: with these four moves, no way there takes fewer steps
  const h = (c: number) => Math.abs(row(c) - row(goal)) + Math.abs(col(c) - col(goal));
  // the cells next to c inside the grid, in the order up, left, right, down
  const neighbors = (c: number) => {
    const out: number[] = [];
    if (c >= width) out.push(c - width);
    if (col(c) > 0) out.push(c - 1);
    if (col(c) < width - 1) out.push(c + 1);
    if (c + width < n) out.push(c + width);
    return out;
  };

  const g = new Array<number>(n).fill(-1); // -1: not found yet
  const parent = new Array<number>(n).fill(-1);
  const closed = new Array<boolean>(n).fill(false);
  const heap: Entry[] = [];
  let expanded = 0;
  g[start] = 0;
  push(heap, [h(start), h(start), start]);
  while (heap.length > 0) {
    const [, , c] = pop(heap);
    if (closed[c]) continue; // a stale entry: c was found cheaper after this one went in, and is done already
    closed[c] = true;
    expanded += 1;
    if (c === goal) break;
    for (const nb of neighbors(c)) {
      if (walls[nb] || closed[nb]) continue;
      if (g[nb] === -1 || g[c] + 1 < g[nb]) {
        g[nb] = g[c] + 1;
        parent[nb] = c;
        push(heap, [g[nb] + h(nb), h(nb), nb]);
      }
    }
  }
  if (!closed[goal]) return { path: [], expanded };
  const path: number[] = [];
  for (let c = goal; c !== -1; c = parent[c]) path.push(c);
  return { path: path.reverse(), expanded };
}
c/algos/a_star.c
/* a* on a grid: dijkstra with a sense of direction. cells are numbered row by row, a wall is a cell you can't stand on, and a move goes up, left, right or down for a cost of 1. every cell found so far waits in a min-heap by f = g + h: g is the cost of the best way to it so far, and h is a guess of the cost left, here the manhattan distance to the goal. on this grid h never guesses more than the real cost, so when the goal comes off the heap the way to it is a shortest one. cells that can't be on a short way have a big f and wait, which is what the same search with h = 0, dijkstra, can't do. the heap is written out here, so the file stands alone. */
#include "a_star.h"

#include <stdlib.h>

/* a heap entry: f first, then h (closer to the goal first), then the cell. every run pops in one
   order */
typedef struct {
    int f, h;
    size_t cell;
} Entry;

/* len entries in an array read as a tree: items[0] is the top, and entry i's children are at
   2i + 1 and 2i + 2. every parent comes before its children. it never grows: astar_run gives it
   room for every push there can be */
typedef struct {
    Entry *items;
    size_t len;
} Heap;

/* whether a comes off the heap before b. no two entries are the same, so one of them always does */
static bool before(Entry a, Entry b) {
    if (a.f != b.f) return a.f < b.f;
    if (a.h != b.h) return a.h < b.h;
    return a.cell < b.cell;
}

static void swap(Entry *a, Entry *b) {
    Entry t = *a;
    *a = *b;
    *b = t;
}

/* an entry goes in at the end and swaps up while it comes before its parent */
static void push(Heap *h, Entry e) {
    size_t i = h->len++;
    h->items[i] = e;
    while (i > 0) {
        size_t parent = (i - 1) / 2;
        if (!before(h->items[i], h->items[parent])) return;
        swap(&h->items[i], &h->items[parent]);
        i = parent;
    }
}

/* the first entry comes off the top. the last one moves up there and swaps down past children that
   come before it. the heap must not be empty: if the top was the only entry, the last one is itself,
   and the swap down stops right away */
static Entry pop(Heap *h) {
    Entry top = h->items[0];
    h->items[0] = h->items[--h->len];
    size_t i = 0;
    for (;;) {
        size_t left = 2 * i + 1, right = left + 1, first = i;
        if (left < h->len && before(h->items[left], h->items[first])) first = left;
        if (right < h->len && before(h->items[right], h->items[first])) first = right;
        if (first == i) return top;
        swap(&h->items[i], &h->items[first]);
        i = first;
    }
}

/* how far apart two rows, or two columns, are */
static int gap(size_t a, size_t b) {
    return (int)(a > b ? a - b : b - a);
}

/* the manhattan distance from c to the goal: with these four moves, no way there takes fewer steps */
static int manhattan(size_t c, size_t goal, size_t width) {
    return gap(c / width, goal / width) + gap(c % width, goal % width);
}

/* g[c] is the cost of the best way to c so far, or -1 before c is found, and parent[c] the cell
   before it on that way. every expansion pushes at most one entry per move, and the start makes one
   more, so 4n + 1 slots hold every entry. the path is allocated last, once its length is known:
   g[goal] + 1 cells, written from the back as the parents are followed. once start is below n, n is
   at least 1, so no allocation is one of 0 bytes */
bool astar_run(AStarResult *found, const bool *walls, size_t n, size_t width, size_t start, size_t goal) {
    *found = (AStarResult){0};
    /* whole rows: a width of 0 goes first, since n % 0 would divide by zero. then a start and goal
       on open cells inside the grid, both checked against n before walls is read, so an empty grid
       never reads it */
    if (width == 0 || n % width != 0) return false;
    if (start >= n || goal >= n || walls[start] || walls[goal]) return false;
    int *g = malloc(n * sizeof *g);
    int *parent = malloc(n * sizeof *parent);
    bool *closed = calloc(n, sizeof *closed); /* calloc: nothing settled yet */
    Heap heap = {malloc((4 * n + 1) * sizeof *heap.items), 0};
    bool ok = g && parent && closed && heap.items;
    if (ok) {
        for (size_t c = 0; c < n; c++) g[c] = parent[c] = -1;
        g[start] = 0;
        int h = manhattan(start, goal, width);
        push(&heap, (Entry){h, h, start}); /* f is g + h, and g is 0 at the start */
    }
    while (ok && heap.len > 0) {
        size_t c = pop(&heap).cell;
        /* a stale entry: c was found cheaper after this one went in, and is done already */
        if (closed[c]) continue;
        closed[c] = true;
        found->expanded++;
        if (c == goal) break;
        /* the cells next to c inside the grid, in the order up, left, right, down */
        size_t around[4], count = 0;
        if (c >= width) around[count++] = c - width;
        if (c % width > 0) around[count++] = c - 1;
        if (c % width < width - 1) around[count++] = c + 1;
        if (c + width < n) around[count++] = c + width;
        for (size_t i = 0; i < count; i++) {
            size_t nb = around[i];
            if (walls[nb] || closed[nb]) continue;
            if (g[nb] == -1 || g[c] + 1 < g[nb]) {
                g[nb] = g[c] + 1;
                parent[nb] = (int)c;
                int h = manhattan(nb, goal, width);
                push(&heap, (Entry){g[nb] + h, h, nb});
            }
        }
    }
    if (ok && closed[goal]) {
        /* the start has g 0 and every cell after it g one more than its parent, so the chain of
           parents from the goal back to the start is g[goal] + 1 cells long */
        found->len = (size_t)g[goal] + 1;
        found->path = malloc(found->len * sizeof *found->path);
        ok = found->path != NULL;
        size_t i = found->len;
        for (int c = (int)goal; ok && c != -1; c = parent[c]) found->path[--i] = (size_t)c;
    }
    free(g);
    free(parent);
    free(closed);
    free(heap.items);
    if (!ok) astar_free(found);
    return ok;
}

void astar_free(AStarResult *found) {
    free(found->path);
    *found = (AStarResult){0}; /* no path, and nothing expanded */
}
swift/algos/AStar.swift
/// a* on a grid: dijkstra with a sense of direction. cells are numbered row by row, a wall is a cell you can't stand on, and a move goes up, left, right or down for a cost of 1. every cell found so far waits in a min-heap by f = g + h: g is the cost of the best way to it so far, and h is a guess of the cost left, here the manhattan distance to the goal. on this grid h never guesses more than the real cost, so when the goal comes off the heap the way to it is a shortest one. cells that can't be on a short way have a big f and wait, which is what the same search with h = 0, dijkstra, can't do.

// a heap entry: f first, then h (closer to the goal first), then the cell. tuples compare in that order, and no two
// entries are the same, so every run pops in one order
private typealias Entry = (f: Int, h: Int, cell: Int)

// adds e at the end, then swaps it up while it comes before its parent
private func push(_ heap: inout [Entry], _ e: Entry) {
    heap.append(e)
    var i = heap.count - 1
    while i > 0 {
        let parent = (i - 1) / 2
        if !(heap[i] < heap[parent]) { return }
        heap.swapAt(parent, i)
        i = parent
    }
}

// takes out the first entry: the last one moves to the top and swaps down past children that come before it
private func pop(_ heap: inout [Entry]) -> Entry {
    let top = heap[0]
    let last = heap.removeLast()
    if heap.isEmpty { return top }
    heap[0] = last
    var i = 0
    while true {
        let left = 2 * i + 1
        let right = left + 1
        var first = i
        if left < heap.count && heap[left] < heap[first] { first = left }
        if right < heap.count && heap[right] < heap[first] { first = right }
        if first == i { return top }
        heap.swapAt(i, first)
        i = first
    }
}

/// the shortest path from start to goal, as cells from start to goal, and how many cells the search expanded: took
/// off the heap and settled, the goal included. walls[c] is true for a wall; the grid has width columns and
/// walls.count / width rows. the path is [] when the goal can't be reached, after every cell it can reach is
/// expanded, and [start] when the start is the goal. a size that isn't whole rows, a cell outside the grid, and a
/// start or goal on a wall trap
public func aStar(_ walls: [Bool], _ width: Int, _ start: Int, _ goal: Int) -> (path: [Int], expanded: Int) {
    let n = walls.count
    precondition(width >= 1 && n % width == 0, "no grid of \(n) cells with \(width) columns")
    for c in [start, goal] {
        precondition(0 <= c && c < n, "no cell \(c)")
        precondition(!walls[c], "cell \(c) is a wall")
    }
    // the manhattan distance to the goal: with these four moves, no way there takes fewer steps
    func h(_ c: Int) -> Int { abs(c / width - goal / width) + abs(c % width - goal % width) }
    // the cells next to c inside the grid, in the order up, left, right, down
    func neighbors(_ c: Int) -> [Int] {
        var out: [Int] = []
        if c >= width { out.append(c - width) }
        if c % width > 0 { out.append(c - 1) }
        if c % width < width - 1 { out.append(c + 1) }
        if c + width < n { out.append(c + width) }
        return out
    }

    var g = [Int?](repeating: nil, count: n) // nil: not found yet
    var parent = [Int?](repeating: nil, count: n)
    var closed = [Bool](repeating: false, count: n)
    var heap: [Entry] = []
    var expanded = 0
    g[start] = 0
    push(&heap, (h(start), h(start), start))
    while !heap.isEmpty {
        let c = pop(&heap).cell
        if closed[c] { continue } // a stale entry: c was found cheaper after this one went in, and is done already
        closed[c] = true
        expanded += 1
        if c == goal { break }
        let step = g[c]! + 1 // a neighbor's g by way of c
        for nb in neighbors(c) {
            if walls[nb] || closed[nb] { continue }
            if g[nb] == nil || step < g[nb]! {
                g[nb] = step
                parent[nb] = c
                push(&heap, (step + h(nb), h(nb), nb))
            }
        }
    }
    if !closed[goal] { return ([], expanded) }
    var path = [goal]
    while let p = parent[path.last!] { path.append(p) } // the start has no parent, so the walk stops there
    return (path.reversed(), expanded)
}
python/algos/a_star.py
"""a* on a grid: dijkstra with a sense of direction. cells are numbered row by row, a wall is a cell you can't stand on, and a move goes up, left, right or down for a cost of 1. every cell found so far waits in a min-heap by f = g + h: g is the cost of the best way to it so far, and h is a guess of the cost left, here the manhattan distance to the goal. on this grid h never guesses more than the real cost, so when the goal comes off the heap the way to it is a shortest one. cells that can't be on a short way have a big f and wait, which is what the same search with h = 0, dijkstra, can't do."""

from __future__ import annotations

from typing import NamedTuple

# a heap entry: f first, then h (closer to the goal first), then the cell. tuples compare item by item, so
# every run pops in one order
Entry = tuple[int, int, int]


class Search(NamedTuple):
    """The path from start to goal, as cells, and how many cells the search expanded."""

    path: list[int]
    expanded: int


def _push(heap: list[Entry], entry: Entry) -> None:
    """Add entry at the end, then swap it up while it comes before its parent."""
    heap.append(entry)
    i = len(heap) - 1
    while i > 0:
        parent = (i - 1) // 2
        if heap[parent] <= heap[i]:
            return
        heap[parent], heap[i] = heap[i], heap[parent]
        i = parent


def _pop(heap: list[Entry]) -> Entry:
    """Take out the first entry: the last one moves to the top and swaps down past children that come first."""
    top = heap[0]
    last = heap.pop()  # only the last slot can go without leaving a hole
    if heap:  # unless that was the only entry
        heap[0] = last
        n = len(heap)
        i = 0
        while True:
            left = 2 * i + 1
            right = left + 1
            first = i
            if left < n and heap[left] < heap[first]:
                first = left
            if right < n and heap[right] < heap[first]:
                first = right
            if first == i:
                break
            heap[i], heap[first] = heap[first], heap[i]
            i = first
    return top


def a_star(walls: list[bool], width: int, start: int, goal: int) -> Search:
    """Return the shortest path from start to goal, as cells, and how many cells the search expanded.

    Expanded means taken off the heap and settled, the goal included. walls[c] is True for a wall; the grid
    has width columns and len(walls) // width rows. The path is [] when the goal can't be reached, after every
    cell it can reach is expanded, and [start] when the start is the goal. A size that isn't whole rows or a
    start or goal on a wall raises ValueError, and a cell outside the grid raises IndexError.
    """
    n = len(walls)
    if width < 1 or n % width != 0:
        raise ValueError(f"no grid of {n} cells with {width} columns")
    for c in (start, goal):
        if not 0 <= c < n:
            raise IndexError(f"no cell {c}")  # a negative cell would count from the end of the list
        if walls[c]:
            raise ValueError(f"cell {c} is a wall")

    def h(c: int) -> int:
        """The manhattan distance to the goal: with these four moves, no way there takes fewer steps."""
        return abs(c // width - goal // width) + abs(c % width - goal % width)

    def neighbors(c: int) -> list[int]:
        """The cells next to c inside the grid, in the order up, left, right, down."""
        out = []
        if c >= width:
            out.append(c - width)
        if c % width > 0:
            out.append(c - 1)
        if c % width < width - 1:
            out.append(c + 1)
        if c + width < n:
            out.append(c + width)
        return out

    g = [-1] * n  # -1: not found yet
    parent = [-1] * n
    closed = [False] * n
    heap: list[Entry] = []
    expanded = 0
    g[start] = 0
    _push(heap, (h(start), h(start), start))
    while heap:
        _, _, c = _pop(heap)
        if closed[c]:
            continue  # a stale entry: c was found cheaper after this one went in, and is done already
        closed[c] = True
        expanded += 1
        if c == goal:
            break
        for nb in neighbors(c):
            if walls[nb] or closed[nb]:
                continue
            if g[nb] == -1 or g[c] + 1 < g[nb]:
                g[nb] = g[c] + 1
                parent[nb] = c
                _push(heap, (g[nb] + h(nb), h(nb), nb))
    if not closed[goal]:
        return Search([], expanded)
    path = []
    c = goal
    while c != -1:
        path.append(c)
        c = parent[c]
    path.reverse()
    return Search(path, expanded)

pitfalls

variants

practice

how real libraries do it

sources

  1. peter e. hart, nils j. nilsson and bertram raphael, a formal basis for the heuristic determination of minimum cost paths (opens in a new tab), ieee transactions on systems science and cybernetics 4(2), 1968, pp. 100–107, with an open copy (opens in a new tab) on nilsson’s stanford page. p. 102 names the algorithm a*, sets f̂ = ĝ + ĥ, and resolves ties arbitrarily but always in favor of a goal node. theorem 1 on p. 103: a* is admissible, sure to find an optimal path, when ĥ never exceeds the true cost. p. 104 states the consistency assumption, a triangle inequality on ĥ, under which a closed node never needs reopening, so step 4’s reopening may be dropped. theorem 2 and its corollary on p. 105: no admissible algorithm with no more information expands fewer nodes, ties aside. p. 106 notes that with every arc costing 1, breadth-first search is a* with ĥ = 0. p. 107 weighs raising ĥ above the airline distance, to x + y: no longer admissible, usually still optimal, and often fewer nodes expanded. ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  2. heapq.rst (opens in a new tab) in cpython 3.15.0, the priority queue implementation notes: tuple comparison breaks when priorities tie and the tasks can’t be compared, and the fix is an entry of the priority, a count and the task, where the count breaks ties in insertion order and is never equal, so two tasks are never compared. the same notes (opens in a new tab) say changing an entry’s priority in place would break the heap, so an entry is marked removed and a new one pushed. ↩ ↩2

  3. astar.py (opens in a new tab) in networkx 3.7: with no heuristic h = 0, the same as dijkstra’s algorithm, and the queue holds the priority, a counter, the node, its cost and its parent, the counter breaking ties in the priority and keeping the heap from comparing nodes. the loop (opens in a new tab) skips a popped node that was queued earlier at a lower cost, and doesn’t queue a neighbor again when its queued cost is no higher. its docstring (opens in a new tab) says an inadmissible heuristic may give a path that isn’t shortest. ↩

  4. astar.rs (opens in a new tab) in petgraph 0.8.3: the open set is a binary heap of MinScored((f, h, g), node), there is no closed set, and a popped node already expanded with a better cost is skipped. scored.rs (opens in a new tab): MinScored compares in reverse by its score so the heap gives out the least score first, and a tuple score compares element by element, f, then h, then g. the docs (opens in a new tab) ask for non-negative edge costs and an admissible estimate that never overestimates the cost to the nearest goal. ↩

  5. astar.rs (opens in a new tab) in the pathfinding crate 4.16.0: SmallestCostHolder orders the heap by estimated cost, smallest first, and on a tie by cost, largest first. the loop (opens in a new tab) discards an entry whose cost is above the node’s recorded cost, since a node may be inserted several times when a better way to it turns up, and the docs (opens in a new tab) say the heuristic must not be greater than the real cost, or a wrong shortest path may be returned. ↩