Lite / Textbooks / Introduction to Intelligent Systems / Chapter 4
4. Search and planning
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.
Figure 4.1. Breadth-first search, cell by cell (described in words)
A 5 by 4 grid with walls. Breadth-first search from the top-left cell writes each free cell's distance in moves: 0, 1, 2, 3 along the top row, then around the walls, reaching the bottom-right goal in 7 moves. Wall cells hold no number.
Explanation
Built from 4 School lessons. Each part is the lesson's own explanation.
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.
Open the Lite lesson: Planning a route before you move
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 Lite 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 Lite 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.
Open the Lite lesson: When exact answers are out of reach
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, in words
Figure 4.2 from Planning a route before you move
Plan the entire route to the flag before you press anything, writing it on paper. Then enter it and press Run all. Did it work first time? Find the shortest safe route you can.
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.
Figure 4.3 from Breadth-first search: a queue explores a map
Keep Breadth-first search selected and step through the first 20 expansions. Notice the 'rings' of equal move count. Then wall off the goal completely and watch what BFS does. Finally, add walls to make the path as long as you can.
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.
Figure 4.4 from When exact answers are out of reach
Start at 4 cities and add one at a time up to 9, watching 'tours tried'. On several random maps, compare the greedy nearest-neighbour route with the exact best. How far off is greedy at its worst?
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
These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.
- Nexus: Autonomous rover (Nexus project)
Plan a rover route around obstacles and compare the number of moves with the shortest path found by breadth-first search.
Open on the full site - Code Lab (Studio)
Implement breadth-first search on a small grid with a queue, then change one cell's cost and switch to Dijkstra's algorithm.
Open on the full site
Practice
Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.
- On an open grid with no walls, what's the fewest Forward moves to get from (0, 0) to (3, 5)?
Answer it in “Planning a route before you move” - 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?
Answer it in “Planning a route before you move” - What would change if BFS used a stack (pop the newest cell) instead of a queue?
Answer it in “Breadth-first search: a queue explores a map” - Why mark a cell visited when it is ADDED to the queue, rather than when it is taken out?
Answer it in “Breadth-first search: a queue explores a map” - On a map where every free cell costs 1, how do BFS and Dijkstra compare?
Answer it in “Project: plan a path that counts the cost” - Why must Dijkstra's step costs be non-negative?
Answer it in “Project: plan a path that counts the cost” - How many distinct round trips (direction ignored) through 8 cities?
Answer it in “When exact answers are out of reach” - Your greedy scheduler beats random scheduling on every test. What should the report claim?
Answer it in “When exact answers are out of reach”
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)
Streaming video uses a lot of data. Everything you need is in the text.
- “Dijkstra's Algorithm - Computerphile” by Computerphile
- “A* (A Star) Search Algorithm - Computerphile” by Computerphile
- “Path Planning with A* and RRT | Autonomous Navigation, Part 4” by MATLAB
- “P vs. NP and the Computational Complexity Zoo” by hackerdashery
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. Field Guide
- Differential drive
- A differential-drive robot has two independently driven wheels on one axle; it steers by turning them at different speeds. Field Guide
- 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. 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
Write it up on paper or in your own notes. Lite never stores what you write.
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 lessons
- Python docs: heapq
Priority queues in the standard library, including notes on using them for scheduling.