Lesson 23 of 231 hour

Graph Search, Costs, and Constraints

Start with the lesson question, connect the representations, and test the model with evidence.

astarpath planningfootprinthard constraintedge costswept motion

Learning objectives

  • Compare reactive rules, state machines, and behavior trees.
  • Explain graph search, costs, constraints, and collision avoidance.
  • Design fallback and replanning behavior under uncertainty.
Lesson flowHook, model, explanationShow guidance

Inspect the opening phenomenon

Predict what changes, then name the evidence.

Apply in the lab

Name the evidence before reading the answer.

Read only what helps

Then use the lab and recall check.

More when needed

Transcript and resources stay available below.

Course progress

AI & Robotics Foundations · Planning and Robot Behavior · Lesson 23

Graph Search, Costs, and Constraints

In progress

Decision challenge

Observe the phenomenon. Then connect the representations.

Use the opening example to make a prediction, identify evidence, and explain which model supports it.

Why Can a Shorter Robot Path Cost More? A* Explained

Why Can a Shorter Robot Path Cost More? A* Explained

Why Can a Shorter Robot Path Cost More? A* Explained

Reference drawerTranscript, source notes, scripts, and package status stay tucked away until you need them.7 files

Lesson reading

live

1 hr

Video script

draft

Transcript fallback

available

courses/ai-robotics/modules/08-planning-and-robot-behavior/lessons/02-graph-search-costs-and-constraints/video-transcript.md

Compare Valid Routes with Cost-Aware A*

draft

25 min

Mastery check

live

7 questions / 8 min

Book section:courses/ai-robotics/modules/08-planning-and-robot-behavior/lessons/02-graph-search-costs-and-constraints/book-section.md
Transcript for accessibility and fallback

Why Can a Shorter Robot Path Cost More? A* Explained Complete narration and visual descriptions for the [2:04 Humanoid Hub tutorial](https://www.youtube.com/watch?v=xK-7JvZuVuY), published 2026-09-30. 0:00 — Six moves. Wrong route. This route is only six moves. So why can't our delivery robot use it? Watch the gap. Visual equivalent: A white delivery robot advances toward the central gap on a six-move straight route. It stops before the opening; the short route alone does not establish that its body fits. 0:06 — A robot is not a point. The map treats the robot like a point. The real circular footprint is one point two units wide. The gap is only one. Visual equivalent: The opening is one unit wide. A magnified circular footprint is 1.2 units across. The attempted red footprint overlaps the walls, marking an invalid proposed placement rather than executed motion. 0:15 — Reject before scoring. Reject the route before scoring it. Expand each obstacle by the robot's radius: forbidden center positions close the gap. Check whole moves, not just endpoints. Visual equivalent: Obstacle exclusion regions expand by radius 0.6 and meet across the opening. A center path through this region is rejected. A separate crossing-edge example shows why clear endpoints are insufficient. 0:27 — Both routes now fit. Now use a smaller, point seven unit robot. Both routes fit. But fitting is a constraint; choosing between valid routes is a cost decision. Visual equivalent: The robot changes to a 0.7-unit diameter. It can pass through the gap. Both the direct path and the longer upper detour are geometrically valid for this smaller disk. 0:37 — Longer can cost less. Count one per move, plus twelve when entering the low-clearance cell. The shortcut costs eighteen. This detour costs fourteen. Longer distance, lower cost. Visual equivalent: The direct route has six unit moves and one surcharge of twelve: total eighteen. The upper detour has fourteen unit moves and no surcharge: total fourteen. The less expensive route is longer. 0:49 — A* adds two costs. A star ranks the frontier using g plus h. g is accumulated cost; h estimates what's left. Here, two plus four gives six. Visual equivalent: The selected example has accumulated cost g=2 and Manhattan lower bound h=4. Their sum f=6 is shown as the frontier priority, not a collision or safety test. 1:00 — Search before motion. Watch the frontier expand. These highlights are search, not robot motion. The costly gap changes the queue. Stop when the goal is selected, not first spotted. Visual equivalent: Successive cells display the actual search expansion trace. The robot remains stationary while the frontier changes and the costly gap affects queue order. The goal must be selected from the queue before this search terminates. 1:12 — Optimal in this model. Our heuristic counts remaining horizontal and vertical steps. Each move costs at least one, so it doesn't overestimate. The guarantee is lowest modeled cost, not real-world safety. Visual equivalent: Horizontal and vertical displacement form the Manhattan lower bound. Allowed moves are cardinal and cost at least one. The result is labeled optimal in this specified model, not guaranteed safe in the physical world. 1:25 — Now the robot moves. Only now does the robot follow the chosen path. Collision checking stays separate. A changing world needs fresh sensing and replanning. Visual equivalent: After search completes, the robot moves along the computed upper detour. The route is checked for swept-footprint clearance. Search and execution are separate phases, not repeated footage. 1:35 — Twelve becomes two. Your turn. If the narrow cell's penalty drops from twelve to two, which route wins? And does that let the larger robot fit? Visual equivalent: The narrow-cell surcharge changes from twelve to two. The screen asks the learner to predict the preferred route and whether changing a cost lets the large disk fit. A three-second pause precedes the answer. 1:48 — Cost cannot create space. The small robot's shortcut now costs eight, beating fourteen. The large robot still cannot fit. First reject invalid moves. Then optimize cost. Try the EduQuest lab. Visual equivalent: The small disk takes the direct route: six plus two equals eight, less than fourteen. The large footprint is still rejected by the unchanged opening. The final rule is: reject invalid moves, then optimize modeled cost. Model and accessibility notes The lab provides the coordinate paths, geometry and exact cost rules without requiring sight, color perception or video playback. Quantities are model units, not physical safety recommendations. English captions are available as assets/v4/captions.en.srt; the same narration appears in a dedicated caption band in the video.

Reading lab

Core explanation

Connect the lesson's words, diagrams, graphs, evidence, and equations.

Driving question

A six-move shortcut crosses a one-unit gap. A detour takes fourteen moves. Which route should the robot use? You cannot answer until you know the robot's footprint and what each move costs.

Learning objectives

  1. Model states, allowed moves, and edge costs.
  2. Calculate f(n) = g(n) + h(n) and explain why the goal must be selected from the frontier.
  3. Separate soft costs from hard feasibility constraints.
  4. Check swept motion, compare search evidence, and describe the limits of a grid model.

Before, during, and after the video

Watch the full 2:04 Humanoid Hub tutorial. Every outcome is also available below and in the descriptive transcript in the Reference drawer; video playback is optional.

  • Before: predict whether a 1.2-unit-wide circular robot fits a 1.0-unit gap. Explain before calculating costs.
  • During: distinguish the moving search highlights from the stationary robot. Notice when actual execution begins.
  • After: lower the narrow-cell penalty from twelve to two. Recalculate the small robot's choice, then ask whether the large robot's feasibility changes.

Non-video visual guide

Same-scale comparison: a 1.2-unit disk overlaps a 1.0-unit opening and is rejected; a 0.7-unit disk fits. Costs cannot change either footprint.

The 9x9 model uses a dashed shortcut costing 6+12=18 and a solid detour costing 14. Both fit the small disk. At penalty 2 the shortcut costs 8.

These diagrams match the worked example. The Practice lab gives the exact coordinates, arithmetic and geometry in text; no interpretation depends on color alone.

1. Define a small, honest model

Our original simulation uses integer grid centers (x,y) from 0 through 8. Start is (1,4), goal (7,4). Two rectangular obstacles occupy 3.5≤x≤4.5, with vertical intervals 1.5≤y≤3.5 and 4.5≤y≤6.5. Therefore the opening between their edges is exactly one unit. In the pictures, y increases downward.

Allowed moves are horizontal or vertical, one unit at a time. The robot is a disk that can stop and rotate in place; a car-like robot needs a different motion model. Room bounds are [-1,9]×[-1,9]. These are model units, not a recommended real robot size or clearance.

ItemMeaning
NodeA possible robot-center position
EdgeAn allowed one-unit move whose entire swept disk is clear
Hard rejectionTouching/crossing an obstacle or boundary; unsupported move
Soft costOne per valid move, plus a nonnegative optional proximity surcharge

2. First decide what is possible

A point can cross the gap. A disk of radius 0.6 cannot: its diameter is 1.2, larger than the gap. Changing a cost cannot shrink the disk. Geometrically expanding an obstacle by the radius identifies forbidden center positions for this circular model. Rounded corners matter: the expansion is not an arbitrary square buffer.

Checking only waypoints is insufficient. In a negative-control test, (2,2) and (6,2) are clear but the segment between them crosses the upper obstacle. The lab rejects unsupported long jumps and separately computes segment clearance. The valid route must pass both endpoint and swept-edge tests.

Nav2's footprint guide distinguishes radius-based and polygon-based representations. Do not generalize this disk example to all robot shapes or planners.

3. Then decide which valid route is preferable

Use a smaller disk, radius 0.35 and diameter 0.7. The shortcut fits. Define each valid edge's cost as 1 + λ when its destination has obstacle/boundary clearance below 0.3; otherwise its cost is 1. Clearance means nearest obstacle/boundary distance minus the disk radius. This intentionally simple surcharge is not Nav2's inflation formula.

The six-move shortcut enters exactly one surcharged center (4,4), where clearance is 0.5−0.35=0.15. The illustrated fourteen-move detour enters none.

Small-robot routeMovesSurcharge at λ=12Total
Through the gap61218
Around the wall14014

The detour wins under this objective, not because longer paths are intrinsically safer. If λ becomes 2, the shortcut costs 8 and wins. This changes the preference, not the collision rule. Real Nav2 inflation includes near-obstacle lethal costs as well as decaying traversal costs; “all inflation is merely a soft preference” is incorrect.

4. A* chooses what to examine next

g is the accumulated cost of the current best route to a candidate; h is a lower-bound estimate of remaining cost in the same units. A* selects the smallest f=g+h from its frontier. At (3,4) here, g=2, h=4, so f=6. The expensive gap has not yet been entered; its surcharge is added when expanding the edge into it. A low f is not a promise that this partial route will win.

For this four-neighbor model, h=|x−7|+|y−4|: at least that many unit moves remain, and every move costs at least one. Removing obstacles and nonnegative surcharges cannot make the estimate too large. The algorithm records improvements to g, skips stale queue entries and terminates when the goal is popped as the lowest-priority-value entry, not when first discovered. See Poole and Mackworth's search discussion.

The heuristic also satisfies consistency, h(u)≤c(u,v)+h(v), on every allowed edge. That supports safe graph-search pruning under these conditions; arbitrary inconsistent heuristics need more care. Consistency and pruning.

Setting h to zero gives uniform-cost search. In this exact fixture A* expands 31 nodes versus 63, both returning total 14. Ties use smaller h, then insertion order. Counts include the selected goal. These are reproducible example results, not a universal performance guarantee.

5. Keep the model's limitations visible

Finite grid optimality is not physical safety. Map freshness, localization error, stopping distance, motion dynamics and moving people are absent. Search visualization is computation; only the later execution scene depicts robot travel. A sealed passage should return NO_PATH, not disable collision checks.

Resolution also changes which geometry is represented. Smaller cells can preserve detail at greater computational cost; coarser sampling can miss obstacles or erase passages depending on occupancy aggregation. Do not claim coarsening always enlarges every obstacle. Nav2 Costmap 2D.

Retrieval check

  1. Why does changing λ not let the large robot through? Geometry is a hard rejection independent of cost.
  2. Why are clear endpoints insufficient? The swept edge can cross an obstacle between them.
  3. If λ=2, which small-robot route wins? The shortcut: 6+2=8 versus 14.
  4. What does “optimal” mean here? Lowest defined cost among allowed paths in the finite static model—not certified safety.

Summary and practice

Represent the robot. Reject invalid motion. Define cost. Search. Verify execution. Run the accessible Practice lab, explain a counterexample, then take the mastery quiz. The lesson AI assistant can provide one hint at a time without completing graded work for you.

Practice labCompare Valid Routes with Cost-Aware A*Open this when you are ready to apply the model, collect evidence, and check your explanation.25 min

Lab: Cost-Aware A* Without Trading Away Safety

Objective

Allow 20–25 minutes. Compare uniform-cost search and A* on the same original static grid. Explain one change to preference and one change to feasibility. Use paper and a calculator, or Node.js 22+ with the standalone model.mjs. No packages, network, paid account or hardware are needed. The former 12×12 simulation is preserved as historical work; this lab and v4 use the 9×9 fixture below.

Save the downloaded model as model.mjs and run it from that folder:

node model.mjs

The script prints its assertions and ordered paths; it does not write files unless --save is explicitly supplied. Read model.mjs before experimenting. It controls no robot.

Materials

  • Paper and a calculator, or optional Node.js 22+.
  • Download the model below; no packages, network access or robot hardware.

Coordinate table and paper fallback

Grid centers are x=0…8, y=0…8. Each cardinal move has length one; y increases down the printed diagram. Start S=(1,4), goal G=(7,4). Upper obstacle: x=3.5…4.5, y=1.5…3.5. Lower obstacle: x=3.5…4.5, y=4.5…6.5. Room bounds: −1…9 on both axes. Touching is invalid.

The direct path is (1,4),(2,4),(3,4),(4,4),(5,4),(6,4),(7,4).

The reference detour is (1,4),(2,4),(2,3),(2,2),(2,1),(3,1),(3,0),(4,0),(5,0),(6,0),(7,0),(7,1),(7,2),(7,3),(7,4).

Use a drawn circle to represent radius 0.6, then radius 0.35. Label obstacles #, the narrow surcharged cell +, start S and goal G. Labels and coordinate paths carry the meaning without color or video.

Steps

  1. Predict: can a radius-0.6 disk take the direct path? Compare its diameter with the gap. Do not assign a cost to an invalid path.
  2. Use radius 0.35. For each valid edge count 1, plus λ when the destination clearance is below 0.3. The direct path has exactly one such destination; the reference detour has none.
  3. Calculate both totals for λ=0, 12 and 2. Name the winner in each case and give the arithmetic.
  4. Run the script. Compare A* with uniform-cost search for radius 0.35 and λ=12. Record expanded nodes, moves, total cost, minimum swept clearance, and validity. Counts include the goal selected from the queue; tie breaking is smaller h, then insertion order.
  5. Negative control: endpoints (2,2) and (6,2) are clear, yet the straight segment crosses the wall. Explain why testing endpoints alone misses the collision. The model rejects a multi-cell edge; segmentClearance independently demonstrates the crossing.
  6. No path: the tests replace both rectangles with a sealed wall. Verify NO_PATH with an empty path. Explain why lowering the clearance penalty is not a remedy.
  7. Resolution reflection: redraw the obstacles using only every second grid center. Explain what occupancy aggregation rule you would need before comparing results. Do not claim that a sparse redraw proves safe navigation or implements a faithful downsampled planner.

Expected Result

For the small robot: λ=0 gives direct cost 6; λ=12 gives direct cost 18 versus detour 14; λ=2 gives direct cost 8. In the fixed weighted run A* expands 31 nodes and uniform-cost search 63, both total 14. The weighted detour's minimum swept clearance is about 0.357 model units. The large robot's direct path is invalid at every λ.

If a cost differs, first check radius, λ, and whether you charged the destination once per edge. If an expansion count differs, inspect heuristic and tie breaking; equivalent optimal paths can exist. If Node is unavailable, submit the coordinate-table arithmetic and geometry argument instead. Model output is not evidence of your own prediction; include your reasoning before and after the run.

Reflection Questions

Submit a metric table, one rejected unsafe shortcut, a labeled path, and a two-sentence explanation of why changing a weight differs from changing the footprint. All work is simulation-only. Never transfer these weights to hardware or bypass collision checking, speed limits, emergency-stop procedures or supervised validation. State which omitted real-world effect would matter first for your proposed application.

Extension Challenge

Propose a different nonnegative surcharge. Predict whether the cost ranking changes and explain which footprint and swept-motion checks must remain unchanged. Test only in this simulation.