TactivergeLite

Lite / Intelligent Robotic Systems / Week 4

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 · Full interactive version

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.

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?

  1. 5
  2. 8
  3. 10
  4. 25
Guess first, then reveal

8: four moves down and four across, in some order. Every shortest path on an open grid has length equal to the Manhattan distance, and BFS finds one of them.

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.

What the interactive shows (text version)

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.

You can also open the interactive on the full site when you have a faster connection.

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

Intuitive

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.

Technical

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.

Mathematical

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).

Applied

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

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

moves

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?

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.

Reflect

Why is it useful that BFS 'fails' cleanly when there is no path? What could happen in a robot if it didn't?

Write your answer on paper or in your own notes. Lite never stores what you write.

← Stacks and queues: who goes next?Halve it again: binary search →