Shortest Paths, MST & Flow · 15 min · free lesson

A* Search: When to Use It

Recognise the problem shape before choosing A* Search.

Core idea

It never exceeds the remaining number of unit orthogonal moves. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Prioritize distance-so-far plus an admissible estimate that never overstates remaining cost.

O((V+E) log V) on this finite four-neighbor grid with consistent heuristic304 execution steps
main · before line 43Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputstart=0,0 goal=3,2

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 43
fn grid_a_star(
    rows: usize,
    cols: usize,
    start: (usize, usize),
    goal: (usize, usize),
    walls: &[(usize, usize)],
) -> Option<usize> {
    let heuristic = |(r, c): (usize, usize)| r.abs_diff(goal.0) + c.abs_diff(goal.1);
    let mut distance = vec![vec![usize::MAX; cols]; rows];
    distance[start.0][start.1] = 0;
    let mut heap =
        std::collections::BinaryHeap::from([std::cmp::Reverse((heuristic(start), 0, start))]);
    while let Some(std::cmp::Reverse((_, cost, (r, c)))) = heap.pop() {
        if cost != distance[r][c] {
            continue;
        }
        if (r, c) == goal {
            return Some(cost);
        }
        for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
            let (nr, nc) = (r as isize + dr, c as isize + dc);
            if nr < 0 || nc < 0 || nr >= rows as isize || nc >= cols as isize {
                continue;
            }
            let next = (nr as usize, nc as usize);
            if walls.contains(&next) {
                continue;
            }
            if cost + 1 < distance[next.0][next.1] {
                distance[next.0][next.1] = cost + 1;
                heap.push(std::cmp::Reverse((
                    cost + 1 + heuristic(next),
                    cost + 1,
                    next,
                )));
            }
        }
    }
    None
}
 
fn main() {
    let result = grid_a_star(4, 4, (0, 0), (3, 2), &[]).map_or("-1".to_string(), |d| d.to_string());
    println!("{result}");
}

Try your own version

Compare the visible input `start=0,0 goal=3,2` with `start=3,3 goal=0,0`. Predict why their results are `5` and `6`. Then change one legal value and explain whether the same invariant, it never exceeds the remaining number of unit orthogonal moves, still applies.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line. Borrowed or moved values are hidden when they cannot be inspected safely.
Five-panel Shortest Paths, MST & Flow infographic; panel 3 illustrates A Star.
A Star: follow panel 3 to see the operation, then trace the lesson's own example.

Understand it

From (0,0) to (3,2), Manhattan distance is 5. Each legal move changes only one coordinate by one, so a five-move path reaches that bound. Walls can only lengthen a route: from (0,0) to (3,0) past walls (1,0),(1,1),(1,2) the estimate is 3 and the true cost is 9. The heap ranks g+h while recorded distances track only g; stale entries are skipped.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: On a 4x4 grid, coordinates are row,col and optional walls=(r,c),... lists cells that cannot be entered. Return the fewest four-neighbor moves from start to goal using A* with the Manhattan heuristic, or -1 when walls block every route. The visible fixture is start=0,0 goal=3,2 and its example result is 5. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for A* Search when it asks for goal-directed pathfinding with useful geometry. Here the concrete task is: On a 4x4 grid, coordinates are row,col and optional walls=(r,c),... lists cells that cannot be entered. Return the fewest four-neighbor moves from start to goal using A* with the Manhattan heuristic, or -1 when walls block every route. The visible input start=0,0 goal=3,2 is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Inspect weight signs and graph direction: non-negative shortest paths, negative edges, and zero-one weights support different algorithms. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Prioritize distance-so-far plus an admissible estimate that never overstates remaining cost. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? Edge weights change what a path means. State whether the objective is minimum distance, a spanning structure, or feasible flow before choosing state. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O((V+E) log V) on this finite four-neighbor grid with consistent heuristic; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 5 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Check disconnected vertices, parallel edges, zero weights, and whether an unreachable result has a defined representation. Use numeric types wide enough for distances, weights, or capacities. In shortest-path heap variants, skip stale queue entries and guard sentinel arithmetic. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Prioritize distance-so-far plus an admissible estimate that never overstates remaining cost.

When to use it: goal-directed pathfinding with useful geometry

Complexity: O((V+E) log V) on this finite four-neighbor grid with consistent heuristic

Input: start=0,0 goal=3,2

Read the code

fn grid_a_star(
    rows: usize,
    cols: usize,
    start: (usize, usize),
    goal: (usize, usize),
    walls: &[(usize, usize)],
) -> Option<usize> {
    let heuristic = |(r, c): (usize, usize)| r.abs_diff(goal.0) + c.abs_diff(goal.1);
    let mut distance = vec![vec![usize::MAX; cols]; rows];
    distance[start.0][start.1] = 0;
    let mut heap =
        std::collections::BinaryHeap::from([std::cmp::Reverse((heuristic(start), 0, start))]);
    while let Some(std::cmp::Reverse((_, cost, (r, c)))) = heap.pop() {
        if cost != distance[r][c] {
            continue;
        }
        if (r, c) == goal {
            return Some(cost);
        }
        for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
            let (nr, nc) = (r as isize + dr, c as isize + dc);
            if nr < 0 || nc < 0 || nr >= rows as isize || nc >= cols as isize {
                continue;
            }
            let next = (nr as usize, nc as usize);
            if walls.contains(&next) {
                continue;
            }
            if cost + 1 < distance[next.0][next.1] {
                distance[next.0][next.1] = cost + 1;
                heap.push(std::cmp::Reverse((
                    cost + 1 + heuristic(next),
                    cost + 1,
                    next,
                )));
            }
        }
    }
    None
}

fn main() {
    let result = grid_a_star(4, 4, (0, 0), (3, 2), &[]).map_or("-1".to_string(), |d| d.to_string());
    println!("{result}");
}

Complete std-only a-star program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace A* Search on input start=0,0 goal=0,0. Which result follows from the documented contract?

Reveal the answer
  1. 1
  2. 0
  3. -1

For this input the result is 0. It never exceeds the remaining number of unit orthogonal moves. Compare this independent fixture with the worked trace: From (0,0) to (3,2), Manhattan distance is 5. Each legal move changes only one coordinate by one, so a five-move path reaches that bound. Walls can only lengthen a route: from (0,0) to (3,0) past walls (1,0),(1,1),(1,2) the estimate is 3 and the true cost is 9. The heap ranks g+h while recorded distances track only g; stale entries are skipped.

Go deeper

Common misconception: “It counts diagonal moves as free”

It never exceeds the remaining number of unit orthogonal moves. From (0,0) to (3,2), Manhattan distance is 5. Each legal move changes only one coordinate by one, so a five-move path reaches that bound. Walls can only lengthen a route: from (0,0) to (3,0) past walls (1,0),(1,1),(1,2) the estimate is 3 and the true cost is 9. The heap ranks g+h while recorded distances track only g; stale entries are skipped.

  1. Concrete transition: From (0,0) to (3,2), Manhattan distance is 5. Each legal move changes only one coordinate by one, so a five-move path reaches that bound. Walls can only lengthen a route: from (0,0) to (3,0) past walls (1,0),(1,1),(1,2) the estimate is 3 and the true cost is 9. The heap ranks g+h while recorded distances track only g; stale entries are skipped.
  2. Independent second fixture: Input start=0,0 goal=0,0 produces 0. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input start=1,1 goal=2,3 produces 3. It never exceeds the remaining number of unit orthogonal moves. The stated work bound is O((V+E) log V) on this finite four-neighbor grid with consistent heuristic. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input start=0,0 goal=3,2 with start=3,3 goal=0,0. Predict why their results are 5 and 6. Then change one legal value and explain whether the same invariant, it never exceeds the remaining number of unit orthogonal moves, still applies.

Connections

  • A* Search: Mental Model: Prioritize distance-so-far plus an admissible estimate that never overstates remaining cost.
  • Challenge: A* Search: On a 4x4 grid, coordinates are row,col and optional walls=(r,c),... lists cells that cannot be entered. Return the fewest four-neighbor moves from start to goal using A* with the Manhattan heuristic, or -1 when walls block every route.
Reveal the Algorithm Atlas answer

5

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: A* Search: When to Use It (courseId "algorithms", lessonId "algorithm.a-star.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.a-star.recognize
Goal: It never exceeds the remaining number of unit orthogonal moves. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.a-star.recognize) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.