Algorithm Atlas · worked example
See the algorithm, step by step
Prioritize distance-so-far plus an admissible estimate that never overstates remaining cost.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
start=0,0 goal=1,1Follow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 43fn 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), (1, 1), &[]).map_or("-1".to_string(), |d| d.to_string());
println!("{result}");
}
Try your own version
Change the independent fixture `start=0,0 goal=1,1` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `start=0,0 goal=3,2`.
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.

Understand it
It never exceeds the remaining number of unit orthogonal moves. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.
For teaching input start=0,0 goal=1,1, the worked program returns 2. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input start=0,0 goal=3,2; predict that result before opening the answer reveal. The precise 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.
Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.
Solve the exact task, not just the visible example: 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. On input start=0,0 goal=3,2, predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.
Build the solution around one maintained claim: Prioritize distance-so-far plus an admissible estimate that never overstates remaining cost. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. Edge weights change what a path means. State whether the objective is minimum distance, a spanning structure, or feasible flow before choosing state. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.
Check both correctness and cost. The intended bound is O((V+E) log V) on this finite four-neighbor grid with consistent heuristic; explain which operation dominates it and how many times the input can trigger that operation. Check disconnected vertices, parallel edges, zero weights, and whether an unreachable result has a defined representation. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.
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), (1, 1), &[]).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.
Practice starter
pub fn solve(input: &str) -> String {
// 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.
// Trim surrounding whitespace; implement parsing and the algorithm.
let _ = input;
todo!("implement a-star")
}
Try it
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.
What success looks like: The private harness prints PASS a-star. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.
Check your understanding
Boundary check for a-star: with input start=1,1 goal=2,3, what result should solve return?
Reveal the answer
342
For this input the result is 3. 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. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.
- Pattern-specific invariant: It never exceeds the remaining number of unit orthogonal moves. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
- Independent typed fixture: The worked call uses
start=0,0 goal=1,1and computes2. Keep parsing separate, then identify the core state before and after this call. - Different legal case: For
start=1,1 goal=2,3, the independently calculated result is3. The complexity discussion uses O((V+E) log V) on this finite four-neighbor grid with consistent heuristic. Verify the state invariant before reasoning about the operation count.
Transfer challenge: Change the independent fixture start=0,0 goal=1,1 in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge start=0,0 goal=3,2.
Connections
- A* Search: When to Use It: goal-directed pathfinding with useful geometry
- Bidirectional BFS: Mental Model: Expand the smaller frontier from each endpoint until the visited sets meet.
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: Challenge: A* Search (courseId "algorithms", lessonId "algorithm.a-star.challenge") Link: https://crabrix.com/learn/algorithms/algorithm.a-star.challenge Goal: It never exceeds the remaining number of unit orthogonal moves. 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. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.a-star.challenge) 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.