Sub topic 8
Breadth-first search for fewest moves
This chapter assumes you can write Python functions, use deque, dictionaries and sets, and that you know a grid can be treated as a graph whose neighbours come from a function like neighbors. Here you use that graph to find the fewest moves between two vertices.
Why a queue gives fewest moves
Breadth-first search (BFS) explores vertices in order of distance from the start. It visits the start, then every vertex one move away, then every vertex two moves away, and so on. A first-in, first-out queue enforces this order: vertices discovered earlier are expanded earlier.
Because of this order, the first time BFS reaches a vertex, it has used the fewest possible moves. This holds only when every move counts the same. If moves have different costs, you need a different algorithm, which a later chapter covers.
The core loop
The search needs three things: a queue of vertices waiting to be expanded, a record of which vertices have been discovered, and a way to list neighbours. A dictionary can do the second job and also store how far each vertex is from the start.
from collections import deque
def neighbors(grid, r, c, diagonal=False):
steps = [(-1, 0), (1, 0), (0, -1), (0, 1)]
if diagonal:
steps += [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for dr, dc in steps:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != '#':
yield nr, nc
def fewest_moves(grid, start, goal):
dist = {start: 0}
queue = deque([start])
while queue:
cell = queue.popleft()
if cell == goal:
return dist[cell]
for nxt in neighbors(grid, *cell):
if nxt not in dist:
dist[nxt] = dist[cell] + 1
queue.append(nxt)
return None
grid = [
"..#.",
".##.",
"....",
]
print(fewest_moves(grid, (0, 0), (0, 3)))This prints 7. The route goes down the left column, across the bottom row, and up the right column.
Two details matter:
- A vertex is marked as discovered when it is added to the queue, not when it is removed. If you mark it on removal, the same vertex can enter the queue many times.
- The function returns
Nonewhen the queue empties without reaching the goal. That result means the goal is unreachable.
Searching a puzzle
BFS never needs to know it is looking at a grid. It needs a start state, a goal test, and a function that lists the next states. Any puzzle with hashable states fits, such as the two-jug puzzle where a state is (a, b).
from collections import deque
def jug_moves(state, caps=(3, 5)):
a, b = state
ca, cb = caps
yield (ca, b)
yield (a, cb)
yield (0, b)
yield (a, 0)
pour = min(a, cb - b)
yield (a - pour, b + pour)
pour = min(b, ca - a)
yield (a + pour, b - pour)
def solve(start, is_goal, moves):
parent = {start: None}
queue = deque([start])
while queue:
state = queue.popleft()
if is_goal(state):
path = []
while state is not None:
path.append(state)
state = parent[state]
return path[::-1]
for nxt in moves(state):
if nxt not in parent:
parent[nxt] = state
queue.append(nxt)
return None
print(solve((0, 0), lambda s: 4 in s, jug_moves))The output is a list of states from (0, 0) to a state holding 4 litres. The parent dictionary replaces dist here, and it also records how each state was reached. The next chapter uses that to rebuild paths.
Common errors
- Using a list as the queue.
list.pop(0)takes time proportional to the list length. Usedeque.popleft(). - Forgetting the visited check. Without it, the search loops forever on any graph with a cycle, and a grid always has cycles.
- Using BFS with unequal costs. BFS minimises the number of moves, not the total cost.
- Using an unhashable state. Lists cannot be dictionary keys. Convert them to tuples.
Exercise
In fewest_moves, what goes wrong if you set dist[nxt] only when you pop nxt from the queue, instead of when you push it?
Show answer
A vertex can be pushed several times before it is first popped, because several neighbours may discover it. The queue grows with duplicates and the work increases. Marking at push time keeps each vertex in the queue at most once.
Exercise
Why does BFS return a fewest-moves answer on a grid but not a cheapest-cost answer on a grid with mud cells that cost 5 to enter?
Show answer
BFS orders vertices by number of moves. A path with fewer moves through mud can cost more than a longer path through open cells, so the first path BFS finds need not be the cheapest.