Turn a room into a grid, then search it for the cheapest route. In this room A* finds the same best path as Dijkstra but opens less than half as many cells. Greedy opens fewer still, and drives a longer path.
Pick a search rule and watch it flood the room toward the yellow goal. Then we build, piece by piece, the configuration space, the grid, the search loop, the heuristic and the proof that A* is right.
You need a little Python and what a distance is. We build the rest from zero.
Lesson 3 of 15 in our follow-along of Stanford AA 274A, Principles of Robot Autonomy I. Every idea is re-taught here in our own words and devices. Before: Lesson 2, Rigid-Body Transforms. Next: Lesson 4, Sampling-Based Planning.
Search rule
Illustrative room: a 20 by 12 grid, 8-connected, straight steps cost 1 and diagonal steps 1.41. A* and Greedy use the straight-line distance to the goal as the guess. The search on this page counts every number live.
Chapter 0
Send a robot straight at its goal and watch the room stop it
You tell a delivery robot "go to the kitchen". It knows where it is and where the kitchen is. It points at the goal and drives. Two seconds later its wheels spin against a wall.
Motion planning computes a sequence of moves that takes a robot from a start to a goal without hitting anything. It respects how the robot can move. It can also make some cost small, such as the path length.
The teal robot must reach the yellow goal behind the U-shaped wall. Choose how it decides, then press Drive.
Illustrative toy on the hero's room, 1 m cells. The aiming robot moves 0.1 m per step along the straight line and stops when its next step would enter a wall cell. The planner runs A* first.
The aiming robot has a local rule: it looks only at the next step. A U-shaped wall traps it. Every step toward the goal is blocked, and the way out leads away from the goal. A planner reads the whole map before the first wheel turns.
Why not try every route and keep the best? Count only the routes that never step back: right or up on each move. A 10 by 10 grid already has 48,620 of them. A 100 by 100 grid has about 2.3 × 1058. We need a search that looks at a tiny part of them and still returns the best.
The symptom is a robot that stalls in a dead end or circles a pillar. To measure it, log the distance to the goal each second: it stops falling. The fix is to plan over the whole map, then follow the plan.
Chapter 1
Drag a round robot and watch its point twin in a space where the walls grow
The robot is a disk 1 m across. To check a move, you ask whether any part of it touches a wall. In the right space, that test is one comparison.
The configuration q is the smallest set of numbers that fixes where the robot is. For a sliding disk, q = (x, y), its centre. The configuration space, or C-space, is the set of every possible q. Call the floor points the body covers at q R(q), and the obstacle points O.
C-free is the set of all q in C such that R of q, intersected with O, is empty.
Place the body at q. If R of q and O share no point, q is in C-free. Everything else is the forbidden space, C-obs.
A wall fills x from 4 to 6 m and y from 4 to 6 m. The disk has radius 0.5 m. At q = (3.7, 5.0) the body reaches x = 4.2, inside the wall. So q is not in C-free.
For a disk there is a short cut: the body touches a wall exactly when the centre is within the radius r of it. Call the distance from q to the nearest obstacle point d(q, O).
q is in C-free if and only if d of q and O is greater than r.
If d is more than r, the robot is clear. So grow every wall outward by r and treat the robot as a point. We call this growth inflation.
Same wall, same q. The nearest wall point is (4, 5), so d = 0.3 m. 0.3 is not more than r = 0.5: collision. The grown wall starts at x = 3.5, and 3.7 is inside it.
Drag the teal disk in the room. Its centre moves as a point in C-space, where each wall has grown by the radius. Then widen the robot until the gap closes.
Illustrative room, 10 m by 7 m. The square is the worked example; the gap to its right is 1.2 m.
The robot fits through the 1.2 m gap while 2r is less than 1.2 m. At r = 0.6 m the grown walls touch: C-space says "no way through" before the robot tries.
A robot that turns and is not round also needs its heading θ. Then C-space has three dimensions. The search in the next chapters works the same in any dimension.
The symptom: the planner calls a long robot stuck in a corridor it fits through. Compare the disk's area with the body's to measure the waste. The fix is to plan with the true shape and heading, as Lesson 4 does.
Chapter 2
Cut the room into cells, join the neighbours, and see a door vanish when the cells are too big
C-free still holds infinitely many points. A computer cannot search them all. So cut the room into a grid of square cells. Mark a cell free if the point robot can stand anywhere in it. Mark it blocked if it touches a grown wall.
Each free cell becomes a node. Each pair of neighbouring free cells gets an edge. Nodes and edges together make a graph. Planning a path is now finding a route through a graph.
| Connectivity | Neighbours | Edge cost (cell side 1) |
|---|---|---|
| 4-connected | up, down, left, right | 1 for every step |
| 8-connected | those 4, plus the 4 diagonals | 1 straight, √2 ≈ 1.41 diagonal |
The edge cost is the true distance between cell centres. Cross a 5 by 5 room from corner to corner, 4 cells over and 4 up. With 4 neighbours that takes 8 steps: cost 8. With 8 neighbours it takes 4 diagonal steps: 4 × 1.41 = 5.66. If you charged 1 for a diagonal, the planner would call a zigzag as short as a straight run.
The grid has a price. Call the side of a cell Δ and the room's length L, both in metres. Call the number of numbers in a configuration d, the dimension.
N equals L over delta, to the power d.
Count the cells along one side, L over delta. Multiply that count by itself once for each of the d dimensions. Halve delta and N grows by 2 to the d.
The room below is 8 m by 5 m, so N = (8 / Δ) × (5 / Δ). At Δ = 0.5 m that is 16 × 10 = 160 cells. At Δ = 0.25 m it is 640 cells.
The pink wall has a door 0.7 m wide. Choose the cell size and the neighbours. Tap a free cell to see its edges.
Cell size
Neighbours
Illustrative room. We draw the wall and the door already grown by the robot's radius. A cell is free only if no part of it touches the wall. Path costs are in metres between cell centres.
At 0.5 m cells the 0.7 m door holds no whole free cell, so the graph has no path. At 0.25 m two cells fit and the path appears. The door never changed; the model of it did.
The symptom is "no path" in a room where a person walks through. To measure it, compare the narrowest gap with the cell size: a gap needs at least one whole cell, and two cells to be safe. The fix is smaller cells near gaps, at the cost of more nodes.
Chapter 3
Step the same loop with two rules and see one of them return the wrong route
Every search in this lesson is one loop. It keeps three records for each node.
Each turn, take one node q off the frontier. For each neighbour q′, call the cost of the edge between them c(q, q′). Price the route to q′ that goes through q.
g-tilde of q-prime equals g of q, plus c of q and q-prime.
Add the edge cost c to g of q. If the sum g-tilde beats the cost on record for q-prime, keep it. Lower g of q-prime, set its parent to q, and put it on the frontier. This step is called relaxation.
In the graph below, B first gets g = 5 from the edge S to B. Later the search expands A, with g(A) = 2. The edge A to B costs 1. g-tilde = 2 + 1 = 3. That beats 5, so B's cost drops to 3 and its parent becomes A.
The searches differ in one place: which frontier node they take next.
| Search | Takes next | Returns |
|---|---|---|
| Breadth-first (BFS) | the oldest node found | the path with the fewest edges |
| Dijkstra | the node with the smallest g | the cheapest path, if no edge costs less than 0 |
| A* (Chapter 5) | the smallest g plus a guess of the cost left | the cheapest path, with fewer nodes expanded |
Choose a rule. Press Step to expand one node. Watch B's cost fall from 5 to 3 under Dijkstra.
Toy graph. Edge costs: S to A 2, S to B 5, A to B 1, A to C 7. B to C 3, C to G 2, B to G 6. This BFS keeps the first parent it finds and never corrects a cost.
Dijkstra expands S, A, B, C, then G, and returns S, A, B, C, G with cost 8. BFS returns S, B, G: only 2 edges, but cost 11. Dijkstra also expanded every node before G. It had no idea where G was. Chapter 4 gives it that idea.
This page uses Dijkstra as a tool. For its proof and its running time, see CLRS 24: Single-Source Shortest Paths.
The symptom is a route with few turns that costs more than it should. To measure it, run Dijkstra on the same graph and compare costs. The fix: use BFS only when every edge costs the same.
Chapter 4
Shade a grid by its guess, and find the cells where the guess overshoots
You know your friend's house is to the north, so you do not search the streets to the south first. Dijkstra does. A heuristic gives the search a sense of direction.
Call the true cheapest cost from a cell q to the goal the cost-to-go, h*(q). You do not know it: knowing it means the problem is solved. So use a cheap estimate, the heuristic h(q). For a grid, call the goal cell (xg, yg), and the gaps to it dx = |x − xg| and dy = |y − yg|.
h-E of q equals the square root of dx squared plus dy squared.
Square dx and dy, add them, and take the square root. That is the crow's flight from q to the goal. No path on the floor is shorter. The Manhattan heuristic adds the gaps instead: dx + dy.
From (1, 1) to the goal (4, 5): dx = 3 and dy = 4. h-E = √(9 + 16) = 5. Manhattan gives 3 + 4 = 7.
A guess is safe only if it never claims the goal is farther than it is.
Zero is at most h of q, and h of q is at most h-star of q, for every cell q.
Compare the guess h of q with the true cost h-star of q in every cell. If h never goes above h-star, the heuristic is admissible: it is optimistic.
On an empty 8-connected grid, the true cost from (1, 1) to (4, 5) is 3 diagonals and 1 straight step. That is 3 × 1.41 + 1 = 5.24. Euclidean 5 ≤ 5.24: admissible. Manhattan 7 > 5.24: it overshoots.
Brighter yellow means a smaller guess. Choose a heuristic and the neighbours. Red marks every cell where the guess beats the true cost. Tap a cell to read both.
Heuristic
Neighbours
Illustrative grid. The true cost h* comes from a Dijkstra search run outward from the goal over the same graph. Octile is the exact cost on an empty 8-connected grid: the longer gap plus 0.41 times the shorter gap.
Manhattan on 8 neighbours overshoots almost everywhere: it cannot see the diagonal short cut. With 4 neighbours the red goes away.
| Grid | Use | Admissible because |
|---|---|---|
| 4-connected | Manhattan, dx + dy | every path needs at least dx + dy steps |
| 8-connected | Octile, or Euclidean | octile is the empty-room cost; Euclidean is shorter still |
A stronger rule is consistency: for every edge, h(q) ≤ c(q, q′) + h(q′). One step never drops the guess by more than the step costs. A consistent heuristic is also admissible. All the safe pairs in the table are consistent.
The symptom is a path a little longer than the best, with no error. To measure it, compare h with a Dijkstra cost-to-go on test maps, as the device does. The fix is the table above.
Chapter 5
Trace A* by hand on a 4 by 4 grid, then step it and count the cells
Dijkstra ranks the frontier by the cost behind each node. The heuristic estimates the cost ahead. A* ranks by their sum. Call that sum f(q).
f of q equals g of q plus h of q.
For each frontier node, add the cost behind, g, to the guess ahead, h. Expand the node with the smallest f. With h = 0 everywhere, f is g and A* is Dijkstra.
On the grid below, cell (1, 0) has g = 1 and h = 5, so f = 6. Cell (2, 2), reached late through (3, 2), has g = 6 and h = 2, so f = 8. A* takes the 6 first.
The loop, in the order you run it:
Now run it by hand. The grid is 4 by 4, 4-connected, every step costs 1. The start is (0, 0), bottom left; the goal is (3, 3), top right. Cells (1, 1) and (2, 1) are walls. The heuristic is Manhattan: h = |x − 3| + |y − 3|. We write each open cell as cell(g, h, f).
| Turn | Expand | Neighbours relaxed | Open set after |
|---|---|---|---|
| 1 | (0,0) f 6 | (1,0) and (0,1): g 1, h 5, f 6 | (1,0)(1,5,6) (0,1)(1,5,6) |
| 2 | (1,0) f 6 | (2,0): g 2, h 4, f 6; (1,1) is a wall | (2,0)(2,4,6) (0,1)(1,5,6) |
| 3 | (2,0) f 6 | (3,0): g 3, h 3, f 6 | (3,0)(3,3,6) (0,1)(1,5,6) |
| 4 | (3,0) f 6 | (3,1): g 4, h 2, f 6 | (3,1)(4,2,6) (0,1)(1,5,6) |
| 5 | (3,1) f 6 | (3,2): g 5, h 1, f 6 | (3,2)(5,1,6) (0,1)(1,5,6) |
| 6 | (3,2) f 6 | (3,3): g 6, h 0, f 6; (2,2): g 6, h 2, f 8 | (3,3)(6,0,6) (0,1)(1,5,6) (2,2)(6,2,8) |
| 7 | (3,3) f 6 | the goal: stop | done |
Follow the parents back from the goal: (3,3), (3,2), (3,1), (3,0), (2,0), (1,0), (0,0). The path costs 6 and runs under the wall. A* expanded 7 cells of 14. Every one had f = 6, the best cost, because here Manhattan equals the true cost in every cell.
Each cell shows g and f once the search reaches it. Press Step, or Play. Then switch to Dijkstra and count again.
The grid of the hand trace. Ties on f go to the smaller h, then to the cell found first.
The symptom is an A* that expands as many cells as Dijkstra. To measure it, log the count of expanded cells for A* and for h = 0. The usual causes are h = 0 by mistake, or ties broken toward the start. Fix both: return the real guess, and break ties on the smaller h.
Chapter 6
Prove that an optimistic guess keeps the best path, then break the guess and watch the path grow
A planner owes you two promises. Complete: if a path exists it finds one, and if none exists it says so. Optimal: the path it returns is the cheapest.
Completeness. The grid has a finite number of cells. A* closes each cell at most once, so it stops. A reachable goal enters the open set, and A* expands it at some point. If the open set empties first, no path exists on this grid. That last part matters: grid A* is resolution complete. It cannot see a door smaller than its cells, as Chapter 2 showed.
Optimality. Suppose A* is about to expand the goal with cost g(G). Since h(G) = 0, f(G) = g(G). Suppose a cheaper path exists, with cost C* < g(G). Some node n on that path sits in the open set now. Call the cost from the start to n along the cheaper path g(n).
f of n equals g of n plus h of n, which is at most g of n plus h-star of n, which equals C-star.
Node n's rank f of n is at most C-star, and C-star is less than g(G), the goal's rank. So A* would expand n before the goal, which is a contradiction. No cheaper path exists. Admissibility is the step that carries the proof.
With made-up numbers: the goal waits with g(G) = 10. A cheaper path costs C* = 8, and its open node n has g(n) = 3 and h*(n) = 5. With an admissible guess h(n) = 4, f(n) = 7, less than 10. So A* expands n first and finds the 8.
Let h overshoot, and the step "at most" fails. Set h(n) = 9 in the example: f(n) = 12, more than 10. A* expands the goal first and returns the path that costs 10. It still finds a path, but not the best one.
Same map, same 8-connected A*. Only the heuristic changes. The faint line is one best path; ties can give another of the same cost.
Illustrative map with 8 walls, found by a search over random maps for a case where Manhattan fails. The page counts every number live.
A* with a closed set never reopens a closed cell. That shortcut is safe only if h is consistent, which the safe pairs in Chapter 4 are.
The symptom is a path 5 to 10% longer than the best, on some maps only. To measure it, run h = 0 on the same maps and compare costs. The fix is an admissible, consistent heuristic for your connectivity.
Chapter 7
Turn up the weight on the guess and watch the search shrink while the path grows
A robot that replans ten times a second has 0.1 s per plan. On a large map even A* can be too slow. Often a slightly longer path is fine if the plan comes in time. One number sets the trade: a weight on the heuristic, ε (epsilon), with ε ≥ 1.
f of q equals g of q plus epsilon times h of q.
Multiply the guess h by epsilon before you add it to g. The search pushes harder toward the goal and expands fewer nodes. The path it returns costs at most epsilon times the best cost, C-star.
In the hero's room the best cost is C* = 18.73. With epsilon = 2, weighted A* expands 61 cells instead of 94 and returns a path of 19.31. The promise allowed up to 2 × 18.73 = 37.46.
Push ε to infinity and g stops mattering: the rank is h alone. That is greedy best-first search. It always steps toward whatever looks closest to the goal. It has no bound on the path cost.
Drag epsilon. The ruler under the grid shows the best cost, the path you got, and the bound epsilon times the best.
The hero's room, Euclidean heuristic, 8-connected. The page measures every count and cost live.
| Rule | Cells expanded | Path cost | Promise |
|---|---|---|---|
| Dijkstra | 208 | 18.73 | best path |
| A*, ε = 1 | 94 | 18.73 | best path |
| Weighted, ε = 2 | 61 | 19.31 | at most 37.46 |
| Greedy | 48 | 20.49 | none |
Greedy looks good on open floors and bad in buildings. It walks into the mouth of every dead end that points at the goal, then crawls out along the wall. To measure it, compare its cost with A* on maps with rooms. The fix is to keep g in the rank: stay near ε = 1 to 2 indoors.
Chapter 8
Paint walls, place the start and goal, choose a rule, and read the count
Every part of the lesson is in this one device. The grid is the cut-up C-space. The pale flood is the closed set, and its edge is the frontier. The pull toward the goal is h. The order of the flood is f = g + εh.
Drag on the grid to paint or erase walls. Use the tool buttons to move the start or the goal. Then press Run.
Tool
Heuristic
Straight steps cost 1, diagonal steps 1.41. A diagonal move may not cut the corner of a wall cell. Ties on f go to the smaller h.
Try four runs, in order.
The count is the score. Every setting finds a path when one exists. They differ in how many cells they had to open to find it.
The symptom is a run that reports "no path" with the goal in plain sight. To measure it, check that the start and goal cells are free and not boxed in by corner rules. The fix is to move them, or to allow the moves your robot can make.
Chapter 9
Give A* real moves, let the map change, and add joints until the grid will not fit
A real robot changes three things. None of them changes the A* loop. They change the graph it searches.
Real moves. A car cannot slide sideways or turn on the spot. So make the edges motion primitives: short moves the car can drive, such as a gentle left arc or a straight run. Lay them on a grid of states that includes the heading. That grid is a state lattice. Only two functions change: the neighbour list and the edge cost. Every path A* returns can then be driven.
| Function | Job | Changes for a car? |
|---|---|---|
| is_free(q) | the collision check | yes: the true body at its heading |
| neighbors(q) | which nodes one move reaches | yes: the motion primitives |
| cost(q, q′) | the price of one move | yes: the arc length |
| solve() | the A* loop | no |
A changing map. A door closes. A person steps out. Rerunning A* from zero works, but it repeats work on a plan that barely changed. D* Lite searches backward from the goal and repairs only the part of the search that the change touched. NASA added Field D*, a planner from the same family, to the Mars Exploration Rovers.
More dimensions. A disk on a floor has d = 2. A car with a heading has d = 3. A 7-joint arm has d = 7. The cell count N = (L / Δ)d from Chapter 2 now explodes.
Each joint adds one dimension. Drag the sliders and watch the cell count against what one computer holds.
One byte per cell. The time line assumes 10 million cell expansions a second, an illustrative speed.
Work the number: 100 cells per joint and 7 joints give 1007 = 1014 cells. At one byte a cell that is 100 terabytes. At 10 million cells a second, touching each cell once takes about 116 days.
The symptom is a planner that runs out of memory before it starts. To measure it, compute N before you build the grid. The fix is to stop building a full grid: sample configurations at random and join them into a graph as you go. That is Lesson 4, sampling-based planning.
Chapter 10
Keep the terms, the numbers and the code in one place
Planning turns a room into a graph and searches it. Grow the walls by the robot's radius and plan for a point. Cut free space into cells. Run one loop that relaxes edges, and rank the frontier by f = g + h with a guess that never overshoots. That returns the cheapest path while it opens few cells.
| Term | Meaning | Number to remember |
|---|---|---|
| C-free | configurations that touch nothing | disk: d(q, O) > r |
| Inflation | grow walls by r, plan for a point | (3.7, 5.0) is 0.3 m from the wall: collision at r = 0.5 |
| Grid size | N = (L / Δ)d | 8 by 5 m at 0.25 m: 640 cells |
| Edge cost | distance between cell centres | 1 straight, 1.41 diagonal |
| Relaxation | g-tilde = g(q) + c(q, q′); keep if lower | B: 5 drops to 3 |
| Admissible | 0 ≤ h ≤ h* | (1,1) to (4,5): Euclidean 5, true 5.24, Manhattan 7 |
| A* | expand the smallest f = g + h | 4 by 4 trace: 7 cells expanded, Dijkstra 14 |
| Weighted A* | f = g + εh; cost ≤ εC* | ε = 2: 61 cells, 19.31 against 18.73 |
| Dimension | one axis per joint | 1007 = 1014 cells |
| Search | Rank | Best path? | Use when |
|---|---|---|---|
| BFS | oldest first | only if all edges cost the same | unweighted graphs |
| Dijkstra | g | yes, if no edge costs less than 0 | no good guess, or many goals |
| A* | g + h | yes, with an admissible h | one goal and a good guess |
| Weighted A* | g + εh | within ε times the best | a deadline |
| Greedy | h | no promise | open floors, speed first |
python import heapq, math def astar(start, goal, neighbors, cost, h, eps=1.0): g = {start: 0.0}; parent = {start: None} open_set = [(eps * h(start), h(start), start)] # (f, h, node): ties go to the smaller h closed = set() while open_set: _, _, q = heapq.heappop(open_set) if q in closed: continue if q == goal: # stop when the goal is expanded path = [] while q is not None: path.append(q); q = parent[q] return path[::-1], g[goal] closed.add(q) for nb in neighbors(q): if nb in closed: continue cand = g[q] + cost(q, nb) # relaxation: g~ = g(q) + c(q, q') if cand < g.get(nb, math.inf): g[nb] = cand; parent[nb] = q heapq.heappush(open_set, (cand + eps * h(nb), h(nb), nb)) return None, math.inf # open set empty: no path on this graph
Based on Stanford AA 274A, Principles of Robot Autonomy I. This page re-teaches the course's third lesson in our own words, devices and toy numbers.
Now press Present or Teach and explain from memory: inflation, the grid, relaxation, admissibility and the 4 by 4 trace. Then go back to the race, pick Greedy, and say why its path is longer.