Go one level per pass when you only need the number of rounds
Some questions ask only how many rounds the search takes, not the distance to each cell. Then you can handle one whole level at a time.
def fewest_steps(grid, start, goal):
seen, queue, steps = {start}, deque([start]), 0
while queue:
# exactly the cells on this level
for _ in range(len(queue)):
r, c = queue.popleft()
if (r, c) == goal:
return steps
for cell in open_neighbors(grid, r, c):
if cell not in seen:
seen.add(cell)
queue.append(cell)
steps += 1
# the queue ran out: unreachable
return -1
range(len(queue)) is worked out once, before the pass starts. So the cells appended during a pass wait for the next one:
| The pass for level 2 on YARD | The queue |
|---|---|
| before the pass | (2,0) (0,2): len(queue) is 2, so it pops 2 |
| after the pass | (2,1) (1,2): level 3, queued during the pass, waits for the next one |
Often you need only the number of rounds: minutes for a fire, days for an infection. Then you don't need a count per cell, and this loop keeps one integer in place of the dict. It's the same search.
On the maze, fewest_steps(MAZE, (0, 0), (0, 3)) is 7, and the corner (2, 5) is 11. On ["..#.", "..#.", "..#."], a column of rock cuts the grid in two, and (0, 0) to (0, 3) returns -1.
In the editor, write level_sizes(grid, start) with that loop: how many cells sit on each level. On YARD, check it against the table of levels in part 2.