Boss

Boss: The Labyrinth Pathfinder

The boss
Boss Fight!
Every passing test breaks a shield.

Beneath the Old Lighthouse lies the Labyrinth, and the last dark lantern hangs at its exit. Pip needs the shortest route, because the torch won't last forever.

The map is a list of strings: S is the start, E the exit, # a wall and . open floor. You may step up, down, left or right.

From distances to a path

In Ripples on a Grid you used BFS to count steps. The shortest path itself needs one more idea. When BFS finds a new square, write down which square it came from:

came_from = {start: None}   # also marks "found"
...
came_from[nxt] = pos        # we reached nxt from pos

When BFS reaches E, walk backwards: E, then came_from[E], then the square before that, until you hit None at the start. Reverse that list and you have the path from S to E.

Assignment

Positions are (row, col) tuples.

Build it in three steps:

  1. find(grid, char): return the position of the first char, or None if it isn't on the map.
  2. neighbors(grid, pos): return a list of the open (not #) positions up, down, left and right of pos that are inside the grid. (You saw this helper in Ripples on a Grid.)
  3. shortest_path(grid): use find to get S and E. Run BFS with a deque and a came_from dict. When you pop E, rebuild the path and return it as a list of positions from S to E (both included). If the queue runs out first, return None.