Queues and BFS: Shortest Path in a Grid
Breadth-first search (BFS) explores in rings: everything 1 step away, then everything 2 steps away, and so on. So the first time it reaches a cell, it got there by a shortest path.
The signal: "fewest steps" or "shortest path" when every step costs the same. Grids, word ladders, and friend-of-a-friend questions are all BFS.
BFS needs a queue. Use collections.deque: append adds to the back and
popleft takes from the front, both O(1). Mark a cell as seen when you add
it, not when you take it out, or the same cell joins the queue many times.
Each cell is handled once, so BFS is O(rows × cols).
A common mistake: list.pop(0) as the queue. It shifts the whole list on
every pop.
Exercise: finish shortest_path. The grid is a list of strings, . is
open and # is a wall. Return the fewest moves (up, down, left, right) from
the top-left cell to the bottom-right cell, or -1 if there is no way.
Press Check to run the tests.