
Ripples on a Grid
Drop a stone in a pond and ripples spread out in rings. Breadth-first search (BFS) explores a map the same way. First it finds every square 1 step from the start, then every square 2 steps away, and so on.
A queue of squares
BFS keeps a queue of squares to explore next. A queue is "first in,
first out", like a line at the ferry dock. collections.deque is a
fast queue: append joins the back, popleft takes from the front.
from collections import deque
dist = {start: 0} # steps to each square found so far
queue = deque([start])
while queue:
pos = queue.popleft() # oldest square waiting
for nxt in neighbors(grid, pos):
if nxt not in dist: # not found yet
dist[nxt] = dist[pos] + 1
queue.append(nxt)
Why the fewest steps?
The queue always holds nearer squares in front of farther ones. So the first time BFS reaches a square, it got there by a shortest route.
The dist dict does two jobs. It stores the answers, and it marks
squares as found, so no square is explored twice.
Backtracking is different. It dives down one path as far as it can (this is called depth-first search, or DFS). It finds a way, but not always the shortest one.
Assignment
The grid is a list of strings. # is a wall and anything else is open
floor. Positions are (row, col) tuples. neighbors(grid, pos) is
written for you: it returns the open squares up, down, left and right.
step_counts(grid, start): use BFS with adeque. Return a dict that maps every reachable open square to its number of steps fromstart.startitself is0.steps_between(grid, start, goal): return the fewest steps fromstarttogoal, or-1ifgoalcan't be reached. Usestep_counts.
The grid is a list of strings. # is a wall and anything else is open
floor. Positions are (row, col) tuples. neighbors(grid, pos) is
written for you: it returns the open squares up, down, left and right.
step_counts(grid, start): use BFS with adeque. Return a dict that maps every reachable open square to its number of steps fromstart.startitself is0.steps_between(grid, start, goal): return the fewest steps fromstarttogoal, or-1ifgoalcan't be reached. Usestep_counts.
Press Run to try your code, then Check to test it.