
Predict
Side Quest: Follow the Ripple
BFS feels like magic until you trace it once by hand. Keep three notes as you go: the square you popped, the queue after it, and the distances found so far.
| popped | queue after | new in dist |
|---|---|---|
| (0, 0) | (1, 0), (0, 1) | (1, 0): 1, (0, 1): 1 |
| … | … | … |
The rules:
- take from the front of the queue, add to the back;
- check neighbours up, down, left, right, in that order;
- a new square gets
dist[pos] + 1; - a square already in
distis ignored. It has been found.
Finish the trace for this tiny map, where # is a wall.
from collections import deque
grid = ["..#",
"..."]
dist = {(0, 0): 0}
queue = deque([(0, 0)])
order = []
while queue:
pos = queue.popleft()
order.append(pos)
r, c = pos
for nr, nc in [(r - 1, c), (r + 1, c),
(r, c - 1), (r, c + 1)]:
inside = 0 <= nr < 2 and 0 <= nc < 3
if inside and grid[nr][nc] != "#":
if (nr, nc) not in dist:
dist[(nr, nc)] = dist[pos] + 1
queue.append((nr, nc))
print(order)
print(dist[(1, 2)])