# a*

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

source: https://learning.anthnydas.com/algos/a-star/

## tl;dr

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

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.[^hart]

## the idea

> **interactive figure:** 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.

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.

the start comes off the heap first: g 0, h 7, f 7. its neighbors get g 1. (2, 1) has h 6, so f 7. (1, 0) and (3, 0) have h 8, so f 9. the smallest f pops next: (2, 1), straight toward the goal.

three more pops at f 7 and the search is at the wall. (2, 3) has no way right. its neighbors up and down get f 9, and so do all the cells in rows 1 and 3 back to the start. the sense of direction is gone for now: every cell with f 9 could be on a 9-step way.

a\* tries the f 9 cells closer to the goal first, by h: (1, 3) and (3, 3), then it works back toward the start, 8 cells in all. none of them leads past the wall, which reaches the top edge: the cells they find, in rows 0 and 4, all have f 11. 12 cells expanded so far.

f rises to 11. (0, 3) and (4, 3) tie on f and on h, and the lower cell number, counting row by row, goes first: (0, 3), a dead end at the top. then (4, 3), under the wall, and from (4, 4) on every pop is one step closer to the goal: h 5, 4, 3, 2, 1.

the goal comes off the heap with f 11 = g 11 + h 0: 11 steps, 20 cells expanded of 44. the same search with h = 0 is dijkstra, and expands 41. so does bfs. the guess cut the work to under half.

## 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.

> **interactive figure:** 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.

> **interactive figure:** 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

```text
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

> **interactive figure:** 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.

- **why manhattan can't be too big.** a move changes the row or the column by 1, so it changes the manhattan distance to the goal by at most 1, and the goal's own distance is 0. any way from a cell to the goal takes at least h moves. a guess like that is called admissible, and it's the whole condition: hart, nilsson and raphael proved that with one, the path a\* returns is a shortest one[^hart]
- **why the goal's turn is the end.** every cell on a shortest way to the goal has f equal to the goal's true distance, and nothing ever has a smaller f than the shortest way through it would cost. so while a cheaper way to the goal is still out there, some cell on it sits on the heap with a smaller f than the goal's, and comes off first. when the goal itself comes off, nothing cheaper is left
- **why done cells can be skipped.** on this grid a move costs 1 and changes h by at most 1, so f never drops along a path: the guess is consistent. cells then come off the heap in nondecreasing f, and the first time a cell comes off its g is final. the 1968 paper's algorithm reopens a closed node when a cheaper way to it turns up, and the paper shows the step is never needed once the guess is consistent[^hart]. the code here never reopens one
- **what a bigger guess trades away.** doubling h makes the search commit harder to the goal's direction. on the page's grid it expands 18 cells instead of 20 and still finds the 11 steps. on the 6 by 3 grid above it expands 10 instead of 12, but it runs along the top row into the wall and returns 9 steps where 7 would do. the paper saw the same trade in 1968, with a road map: a guess above the airline distance is no longer admissible, usually still finds the shortest route, and often expands fewer nodes[^hart]
- **h = 0 is dijkstra.** with no guess, f is g, and the heap settles the closest cell next. on a grid where every move costs 1 that's bfs with extra steps: the same cells in nearly the same order, 41 of 44 on the page's grid either way

## complexity

|          | a\*        | h = 0      | bfs  |
| -------- | ---------- | ---------- | ---- |
| per cell | O(log n)   | O(log n)   | O(1) |
| worst    | O(n log n) | O(n log n) | O(n) |
| space    | O(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.

> **interactive figure:** 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`

```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`

```rust
//! 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`

```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`

```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`

```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`

```python
"""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

- **a guess that's too big.** it looks like a faster a\*, and often is, but the path isn't a shortest one any more. on the 6 by 3 grid above, doubling the manhattan distance returns 9 steps where 7 exist. if the goal is a good route, not the best, that's weighted a\*, below. if it's the shortest, the guess has to stay under the real cost from every cell
- **a guess that ignores the moves allowed.** manhattan distance is safe with four moves because every move covers one row or one column. allow diagonal moves and one move covers both: a cell 3 rows and 3 columns away is 3 moves off, not 6, and manhattan overestimates. the 1968 paper's road map is the mirror case: roads go any direction, so rows plus columns is more than the airline distance there too[^hart]. the guess has to fit the moves
- **ties that wander.** on an open grid every cell between the start and the goal has the same f. break the ties by cell number alone and the search expands the lot: all 64 cells of an open 8 by 8 grid, corner to corner, where the smaller-h rule expands 15, the path and nothing else. on the page's grid it's 26 against 20. python's heapq compares tuples element by element and recommends a unique count in the entry so it never reaches the payload[^heapq]: here that's the cell number, last
- **skipping done cells with a guess that isn't consistent.** a guess can stay under the real cost and still drop by more than a move's cost between neighbors. then a cell can come off the heap before its cheapest way is found, and skipping it from then on loses the shortest path. the original algorithm reopens such a cell, and the paper shows a consistent guess makes that step unnecessary[^hart]. straight-line and manhattan distances are consistent. a guess that mixes rules per cell may not be
- **stopping when the goal is found, not when it comes off the heap.** the first way found to the goal is the first one anybody looked at, not the cheapest. on this grid the two happen to agree, since a neighbor with a cheaper g would have come off the heap first, so a grid test won't catch the bug. with weighted edges it bites. wait for the goal's turn
- **changing an entry on the heap.** a cheaper way to a cell doesn't update its old entry: nothing in a binary heap can find it. push a new entry and skip the old one when it comes off, the way the 4 by 4 grid in the tests does: 13 pushes for 12 cells, and one stale pop. the heapq docs give the same advice, marking the old entry removed[^heapq]

## variants

- **diagonal moves.** with eight moves, manhattan overestimates. the octile distance fits: the bigger of rows and columns apart, plus about 0.41 times the smaller, for diagonals that cost √2. with diagonals that cost 1, the bigger of the two alone
- __weighted a_._\* f = g + w·h with w above 1. it usually expands fewer cells, and its path costs at most w times the shortest. the doubled guess above is w = 2
- **greedy best-first.** f = h alone: straight at the goal, no memory of the cost so far. fast, and the path can be far from shortest
- __ida_._\* a depth-first search with a cap on f that rises each round. it keeps only the current path in memory, which is what makes puzzles with huge state spaces fit, at the price of repeating work each round
- **jump point search.** on an open grid most cells are expanded only to be passed through. jumping along straight runs and stopping at the cells where a wall forces a choice expands far fewer, and still finds a shortest path
- **bidirectional search.** one search from each end, until the two frontiers meet. the stopping rule is subtle with a\*, since the first meeting isn't always on a shortest path
- **weighted graphs.** the same loop with g\[c] + w in place of g\[c] + 1, on adjacency lists instead of a grid: the [dijkstra](/algos/dijkstra/) page, plus a heuristic. with h = 0 it is dijkstra, and on unit edges [bfs](/algos/bfs/) does the same job without the heap

## practice

- [shortest path in binary matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/): eight moves on a grid. bfs is enough, and a\* with the bigger of rows and columns apart as h cuts the cells
- [open the lock](https://leetcode.com/problems/open-the-lock/): states are four wheels. h is the turns each wheel still needs, added up
- [sliding puzzle](https://leetcode.com/problems/sliding-puzzle/): states are boards. h is the manhattan distance of every tile to its place, added up
- [shortest path in a grid with obstacles elimination](https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/): the state is the cell and the eliminations left. manhattan is still a floor
- [cut off trees for golf event](https://leetcode.com/problems/cut-off-trees-for-golf-event/): a shortest path per tree, in order of height. each leg is a bfs, or an a\* with manhattan
- [minimum moves to move a box to their target location](https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location/): the state is the box and the player. h is the box's manhattan distance to the target

## how real libraries do it

- **networkx.** `astar_path` takes a heuristic function, or none, which is h = 0 and dijkstra. its heap entries hold f, a running count, the node, its cost and its parent: the count breaks ties on f in the order the entries went in, and keeps the heap from comparing nodes. a popped node that was explored already is skipped when it was queued at a lower cost than the one popped, and a neighbor already queued at a cost no higher isn't queued again[^networkx]
- **petgraph.** `astar` scores each entry by the tuple (f, h, g) in a min-heap, so a tie on f goes to the smaller h, as here. it keeps no closed set: a popped node whose recorded cost is better than the entry's is skipped. its docs ask for non-negative costs and an estimate that never overestimates[^petgraph]
- **the pathfinding crate.** `astar` orders its heap by f, and on a tie by the larger g, the entry furthest along, which is the smaller h again. an entry whose cost is above the node's recorded cost is discarded as a stale copy[^pathfinding]
- **everywhere else.** games and map services carry their own, tuned to their maps: a grid, a navigation mesh, or roads with turn costs. the loop is the one on this page

[^hart]: peter e. hart, nils j. nilsson and bertram raphael, [a formal basis for the heuristic determination of minimum cost paths](https://doi.org/10.1109/TSSC.1968.300136), ieee transactions on systems science and cybernetics 4(2), 1968, pp. 100–107, with an [open copy](http://ai.stanford.edu/~nilsson/OnlinePubs-Nils/PublishedPapers/astar.pdf) 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.

[^networkx]: [astar.py](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/algorithms/shortest_paths/astar.py#L100-L115) 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](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/algorithms/shortest_paths/astar.py#L137-L161) 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](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/algorithms/shortest_paths/astar.py#L29-L35) says an inadmissible heuristic may give a path that isn't shortest.

[^petgraph]: [astar.rs](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/algo/astar.rs#L94-L132) 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](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/scored.rs#L3-L11): `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](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/algo/astar.rs#L20-L26) ask for non-negative edge costs and an admissible estimate that never overestimates the cost to the nearest goal.

[^pathfinding]: [astar.rs](https://github.com/evenfurther/pathfinding/blob/v4.16.0/src/directed/astar.rs#L314-L341) 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](https://github.com/evenfurther/pathfinding/blob/v4.16.0/src/directed/astar.rs#L103-L115) 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](https://github.com/evenfurther/pathfinding/blob/v4.16.0/src/directed/astar.rs#L22-L25) say the heuristic must not be greater than the real cost, or a wrong shortest path may be returned.

[^heapq]: [heapq.rst](https://github.com/python/cpython/blob/v3.15.0/Doc/library/heapq.rst#L265-L287) 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](https://github.com/python/cpython/blob/v3.15.0/Doc/library/heapq.rst#L300-L325) say changing an entry's priority in place would break the heap, so an entry is marked removed and a new one pushed.

## related

- https://learning.anthnydas.com/algos/dijkstra.md
- https://learning.anthnydas.com/algos/bfs.md
- https://learning.anthnydas.com/ds/heap.md
