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?
About 45 min · 3 goals · Checked by automated tests
1.Why should I care?
Breadth-first search (BFS) is the simplest planner that is guaranteed to find a route with the fewest moves. It's also a perfect showcase for this week: a deque for the frontier, a set for visited cells, a dict for how you got to each cell.
- ◇ Explain how breadth-first search uses a queue to explore cells in order of distance.
- ◇ Implement BFS on a grid with a visited set and a came-from dict, and rebuild the path.
- ◇ Predict when no path exists and how the search behaves.
2.Discover
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.
Loading the interactive…
Can't use the interactive? Read a description instead
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.
3.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
On an open 6-row × 9-column grid, BFS plans from (0, 0) to (5, 8). How many moves are in its path?
4.Predict
On an open 5 × 5 grid (moves up, down, left, right), how many moves does BFS's path take from the top-left corner to the bottom-right?
Guess first. Being wrong here is how the surprise works.
5.Understand
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.
Explain it another way
Drop ink at the start. It spreads one cell further each tick. The first tick it reaches the goal tells you the shortest number of moves, and the way the ink arrived is the path.
Each cell is enqueued at most once and each edge is checked a constant number of times, so BFS on a grid with V cells runs in O(V) time and uses O(V) memory for the queue, visited set and came-from dict.
Let d(v) be the true fewest-moves distance. By induction, BFS dequeues all cells with d = k before any with d = k + 1, because each is enqueued by a cell at distance k − 1. So the first time the goal is dequeued its recorded path has length d(goal).
Warehouse robots and game characters on tile maps often use BFS (or its weighted relatives) to plan around shelves and walls many times a second.
Worked example 1
BFS on a text map, returning the path as a list of cells.
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))) # []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.
6.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 2
What would change if BFS used a stack (pop the newest cell) instead of a queue?
Practice 3
Why mark a cell visited when it is ADDED to the queue, rather than when it is taken out?
Practice 4
The goal is completely surrounded by walls. What does BFS do?
Practice 5 · a fresh version every time
A robot cell queues jobs in arrival order: from collections import deque; q = deque(); q.append(3); q.append(28); q.append(23); q.popleft(); q.popleft(); q.popleft(); q.append(23); q.popleft(). What value does the final q.popleft() return?
7.Apply it
Implement bfs as a function that takes a GridMap object (from week 2) and uses only its neighbours() method. Test it on a corridor, a map that forces a detour, and a map with an unreachable goal. Count how many cells it expands on an open 20 × 20 grid from corner to corner.
8.Reflect
Concepts: Path planning and search · Lists, dictionaries and tabular data