Textbooks/Introduction to Intelligent Systems/Chapter 4Lite (plain text) version
4Search and planning
Version 1 · Technically checked (automated checks only) · 4 source lessons · 8 practice items
Introduction
Planning means looking ahead before acting. On a map divided into cells, a plan is a path, and search algorithms find it systematically. This chapter starts with planning a route by hand, uses a queue to make breadth-first search find the fewest moves, adds costs so Dijkstra's algorithm finds the cheapest path, and ends with problems such as visiting many places in the best order, where exact answers become impossibly slow and good heuristics take over.
Explanation
This chapter is built from 4 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.
4.1 Planning a route before you move
Rover drivers on Earth plan a whole day of driving in one go, then hit send. How do they make sure it doesn't end in a crater?
A plan is a sequence
A route plan is a list of moves from start to goal that avoids every obstacle on the map. Writing it is like writing an algorithm, except the 'bugs' are walls and craters.
Comparing routes
Several routes may work. Engineers compare them: shorter (fewer moves, less energy), safer (further from hazards), or easier to check (passing landmarks the robot can see). The shortest route isn't always the best.
Plans need checkpoints
Real wheels slip and maps are imperfect, so a plan alone is open-loop. Robots add checkpoints: stop, measure where you really are, correct, continue. Planning ahead plus checking along the way combines the best of both.
Common mix-ups
- A good plan doesn't need sensors.
✓ Plans are open-loop. Sensors and checkpoints catch slips and surprises. - The shortest route is always best.
✓ Safety, energy and how easy it is to check position matter too.
4.2 Breadth-first search: a queue explores a map
Put a robot in a maze and flood it outwards one step at a time. Why does the first time the flood touches the goal give the shortest route?
The frontier is a queue
Start with the start cell in a queue. Repeatedly take the oldest cell, and add each unvisited free neighbour to the back. Because cells come out in the order they went in, every cell 1 move away is processed before any cell 2 moves away, and so on.
Visited set and came-from dict
Mark a cell visited when you add it to the queue, so it is never queued twice. Record came_from[neighbour] = current. When you reach the goal, follow came_from back to the start and reverse: that's the path.
Guarantees and limits
BFS always finds a path with the fewest moves if one exists, and reports failure after visiting every reachable cell if not. It ignores terrain cost: a short path through mud beats a long path on tarmac. Fixing that is Dijkstra's job in the term project.
Common mix-ups
- BFS finds the cheapest route.
✓ It finds the route with the fewest moves. With terrain costs you need a cost-aware planner such as Dijkstra. - Search algorithms 'see' the whole map at once.
✓ They only ever look at the neighbours of the cell they are expanding; the map knowledge comes from the order they expand cells.
Open the full lesson: Breadth-first search: a queue explores a map →
4.3 Project: plan a path that counts the cost
BFS finds the fewest moves, straight through the mud. Your rover's battery would rather go round. How does the planner learn to care?
From queue to priority queue
BFS takes the oldest cell; Dijkstra takes the cheapest-so-far cell. Python's heapq keeps a list as a priority queue: heappush(pq, (cost, cell)) and heappop(pq) returns the smallest cost in O(log n). When a cell is popped, its cost is final.
Relax the neighbours
For each neighbour, the candidate cost is cost[cell] + step_cost(neighbour). If that beats the best known cost, record it, set came_from, and push it. Old, worse entries may stay in the heap; skip them when popped if the cell is already finished.
Project structure
grid.py (a GridMap class with neighbours and cost), planners.py (bfs and dijkstra as functions taking a map), experiment.py (timing and counting), test_planners.py (corridor, detour, unreachable goal, uniform-cost map where both agree). Each planner returns the path, its cost and the number of cells expanded.
Common mix-ups
- Dijkstra is just a slower BFS.
✓ It solves a different problem: cheapest route under varying costs. On uniform costs it agrees with BFS. - The fewest-moves path is the best path.
✓ Best depends on the cost you care about: energy, time, risk. Put that cost in the map.
Open the full lesson: Project: plan a path that counts the cost →
4.4 When exact answers are out of reach
A delivery van must visit 20 shops. Trying every route would take a fast computer about two years. How do real route planners answer in a second?
Tractable means polynomial
A problem is usually called tractable if some algorithm solves it in O(n^k) time for a fixed k. Sorting, shortest paths (Dijkstra) and linear systems are tractable. Problems whose best known algorithms take 2ⁿ or n! time become impossible to solve exactly beyond a few dozen items, whatever the hardware.
P, NP and NP-hard, informally
P: problems solvable in polynomial time. NP: problems where a proposed answer can be checked in polynomial time (is this route shorter than 500 km? add up its legs). NP-hard: at least as hard as every NP problem; a fast algorithm for one would give fast algorithms for all. Nobody has proved P ≠ NP, but no one has found a polynomial algorithm for an NP-hard problem either, so engineers plan as if none exists.
Heuristics and approximations
A heuristic (nearest neighbour, greedy packing, simulated annealing) is fast but has no promise about quality. An approximation algorithm comes with a proof: for travelling-salesperson maps that obey the triangle inequality, Christofides' algorithm is never worse than 1.5× optimal. Either way, measure the gap on cases small enough to solve exactly, as the explorer does.
Common mix-ups
- NP means 'not polynomial'.
✓ It means 'nondeterministic polynomial': solutions are checkable in polynomial time. P is inside NP. - If a problem is NP-hard, engineers cannot solve it.
✓ They solve large instances well with heuristics, approximations and solvers, and small ones exactly.
Worked examples
Planning a route before you move: example 1
On the grid robot, compare route A (up 2, east 4, up 2) with route B (east 1 first). Which is valid?
Solution
Route B: Turn right, Forward → (1, 0). Then up: Turn left, Forward → (1, 1), which is a wall. So B fails. Route A: Forward ×2 to (0, 2), Turn right, Forward ×4 to (4, 2), Turn left, Forward ×2 to (4, 4). Valid: 8 Forward moves, 2 turns.
Breadth-first search: a queue explores a map: example 1
BFS on a text map, returning the path as a list of cells.
Solution
from collections import deque
def bfs(rows, start, goal):
"""Fewest-move path from start to goal on a map of strings ('#' = wall), or [] if none."""
h, w = len(rows), len(rows[0])
queue = deque([start])
came_from = {start: None} # doubles as the visited set
while queue:
cell = queue.popleft()
if cell == goal:
path = []
while cell is not None:
path.append(cell)
cell = came_from[cell]
return path[::-1]
r, c = cell
for n in [(r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)]:
nr, nc = n
if 0 <= nr < h and 0 <= nc < w and rows[nr][nc] != "#" and n not in came_from:
came_from[n] = cell
queue.append(n)
return []
grid = ["....",
".##.",
"...."]
path = bfs(grid, (1, 0), (1, 3))
print(len(path) - 1, path) # 5 [(1, 0), (0, 0), (0, 1), (0, 2), (0, 3), (1, 3)]
print(bfs([".#.", "##.", "..."], (0, 0), (2, 2))) # []Project: plan a path that counts the cost: example 1
Dijkstra on a cost grid (0 = wall), returning path, cost and cells expanded.
Solution
import heapq
def dijkstra(costs, start, goal):
"""costs: list of rows of ints (0 = wall, else cost of entering). Returns (path, cost, expanded)."""
h, w = len(costs), len(costs[0])
best = {start: 0}
came_from = {start: None}
done = set()
pq = [(0, start)]
while pq:
c, cell = heapq.heappop(pq)
if cell in done:
continue # a stale, more expensive entry
done.add(cell)
if cell == goal:
path = []
while cell is not None:
path.append(cell)
cell = came_from[cell]
return path[::-1], c, len(done)
r, col = cell
for n in [(r - 1, col), (r, col + 1), (r + 1, col), (r, col - 1)]:
nr, nc = n
if 0 <= nr < h and 0 <= nc < w and costs[nr][nc] > 0 and n not in done:
new = c + costs[nr][nc]
if new < best.get(n, float("inf")):
best[n] = new
came_from[n] = cell
heapq.heappush(pq, (new, n))
return [], float("inf"), len(done)
terrain = [[1, 1, 1, 1, 1],
[1, 9, 9, 9, 1],
[1, 9, 9, 9, 1],
[1, 1, 1, 1, 1]]
path, cost, expanded = dijkstra(terrain, (1, 0), (1, 4))
print(len(path) - 1, cost) # 6 6 (BFS would take 4 moves costing 28)When exact answers are out of reach: example 1
How many distinct round trips through 12 cities, ignoring direction?
Solution
(12 − 1)!/2 = 39,916,800/2 = 19,958,400. At a million tours a second that is 20 s; at 15 cities it is 43.6 billion tours, about half a day.
When exact answers are out of reach: example 2
A greedy route is 112 km and the exact best is 100 km. Report the heuristic's quality.
Solution
Gap = (112 − 100)/100 = 12%, ratio 1.12. One map is one data point: report the worst and average gap over many maps before trusting it.
Interactive figures
Interactive figure (online). Description: The grid robot can be replaced by squared paper: draw a 6-by-6 grid with walls at (1, 1), (2, 1), (3, 1), (3, 3) and (2, 4), start at (0, 0) facing north and the flag at (4, 4). The shortest safe route goes up 2, east 4, up 2: Forward, Forward, Turn right, Forward ×4, Turn left, Forward, Forward.
Interactive figure (online). Description: The planner shows a 7 × 10 grid with a start on the left and a goal on the right, a wall in column 5 rows 1 to 5, and a rough patch. BFS expands cells in rings of increasing move count and returns a fewest-moves path around the end of the wall. Walling off the goal makes BFS expand every reachable cell and report no path.
Interactive figure (online). Description: The explorer draws 4 to 9 random cities with two routes: the exact best tour (found by trying all (n−1)!/2 tours) and the greedy nearest-neighbour tour. A table reports tours tried, both lengths and the percentage gap; at 20 cities brute force would need about 6×10¹⁶ tours.
Laboratory
Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.
Nexus project
Nexus: Autonomous rover
Plan a rover route around obstacles and compare the number of moves with the shortest path found by breadth-first search.
Open Nexus: Autonomous rover →Studio
Code Lab
Implement breadth-first search on a small grid with a queue, then change one cell's cost and switch to Dijkstra's algorithm.
Open Code Lab →
Guided practice
Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.
- On an open grid with no walls, what's the fewest Forward moves to get from (0, 0) to (3, 5)?
- Route A is 10 moves and passes right beside a crater. Route B is 12 moves and stays well clear. Which would a careful engineer pick?
- A, it's shorter
- B, it's safer
- Neither
- What would change if BFS used a stack (pop the newest cell) instead of a queue?
- Nothing
- It would become depth-first search: it still explores, but the first path found need not be the shortest
- It would find shorter paths
- It would crash
- Why mark a cell visited when it is ADDED to the queue, rather than when it is taken out?
- It looks neater
- Otherwise the same cell can be queued many times by different neighbours, wasting time and memory
- Python requires it
- So the path is reversed
- On a map where every free cell costs 1, how do BFS and Dijkstra compare?
- Dijkstra finds cheaper paths
- Both find paths with the same cost (fewest moves); BFS avoids the heap's log factor
- BFS finds cheaper paths
- Dijkstra fails on uniform costs
- Why must Dijkstra's step costs be non-negative?
- heapq can't store negative numbers
- A finished cell's cost is assumed final; a negative step later could make a cheaper route to it
- Negative numbers are slower
- Python forbids them in tuples
- How many distinct round trips (direction ignored) through 8 cities?
- Your greedy scheduler beats random scheduling on every test. What should the report claim?
- It is optimal
- It is better than random on these tests; its gap to optimal is measured on small cases where the optimum can be computed
- NP-hard problems cannot be evaluated
- Nothing until P vs NP is solved
Engineering applications
Warehouse robots
Warehouse robots plan on a grid of floor cells. Costs on busy aisles steer them onto quieter routes, so the cheapest path is often longer than the shortest one.
Delivery rounds
Ordering twenty delivery stops perfectly is out of reach, but a greedy route improved by swapping pairs of stops is usually within a few per cent of the best, which is what route planners use.
Watch
Optional verified videos. Nothing loads from YouTube until you press play.
- Dijkstra's Algorithm - Computerphile (Computerphile)
- A* (A Star) Search Algorithm - Computerphile (Computerphile)
- Path Planning with A* and RRT | Autonomous Navigation, Part 4 (MATLAB)
- P vs. NP and the Computational Complexity Zoo (hackerdashery)
Chapter summary
- A plan on a grid is a path; search explores possibilities in a systematic order.
- Breadth-first search uses a queue, so it reaches every cell first by a fewest-moves path.
- Dijkstra's algorithm uses a priority queue and finds cheapest paths when every step cost is non-negative.
- Some problems grow exponentially; heuristics give good answers fast but must be reported honestly as approximate.
Glossary
- Odometry
- Odometry estimates a robot's position and heading by adding up how far its wheels have turned since a known start.
- Differential drive
- A differential-drive robot has two independently driven wheels on one axle; it steers by turning them at different speeds.
- Coordinate frame
- A coordinate frame is an origin plus a set of axes used to describe positions and directions. Robots use several: world, base, each joint, sensors and the tool.
Definitions from the Field Guide.
Project: Plan, then price, a route
Draw a 10 by 10 map with walls and a few expensive cells such as sand. Find the fewest-moves path with breadth-first search and the cheapest path with Dijkstra's algorithm. Report both paths, their lengths and costs, and when you would choose each.
Deliverables
- The map with costs
- Both paths with length and cost
- A one-paragraph comparison
Keep your work in your Engineering Journal; it stays private unless you choose to share it.
References
- Edsger W. Dijkstra (1959). "A Note on Two Problems in Connexion with Graphs". Numerische Mathematik 1, 269–271.
- Peter E. Hart et al. (1968). "A Formal Basis for the Heuristic Determination of Minimum Cost Paths". IEEE Transactions on Systems Science and Cybernetics 4(2), 100–107.
- Stuart Russell and Peter Norvig (2020). Artificial Intelligence: A Modern Approach, 4th edition. Pearson.
Further reading from the source lessons
- Python docs: heapq ↗Priority queues in the standard library, including notes on using them for scheduling.
Publication record
- Version
- 1
- Status
- Technically checked (automated checks only)
- Technical review
- Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
- Written by
- Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
- Licence
- All rights reserved by the founders unless a licence is approved.
- Corrections
- None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.