100 XP

95. Shortest way through a maze

Advanced graphs grids queues

A maze is a list of rows, each a string of the same length. S is the start, E the exit, # a wall, and . open floor. Each step moves one cell up, down, left or right, never into a wall and never off the maze.

Write a function shortest_path(maze) that returns the fewest steps from S to E, or -1 if walls cut the exit off from the start.

  • There is exactly one S and one E.
  • S and E are open cells, like ..

Exploring one route as deep as it goes can find a long way round first. A breadth-first search looks at every cell one step away, then every cell two steps away, and so on, so the first time it reaches the exit is by a shortest way.

Example 1

Inputmaze = ["S..", ".#.", "..E"]
Output4
ExplanationRound the wall either way: 4 steps.

Example 2

Inputmaze = ["S#E"]
Output-1
ExplanationThe wall cuts the exit off.

Example 3

Inputmaze = ["SE"]
Output1
ExplanationThe exit is right next to the start.

Constraints

  • maze has 1 to 20 rows of 1 to 20 characters each, all the same length, made of S, E, # and ..

Submit also runs 8 more tests you can't see.

Practises Modules and Imports (lesson 22).

Code
def shortest_path(maze):
    """Find the fewest steps from S to E.

    maze: list of str, rows of "S", "E", "#" and "."
    Returns: int, the fewest steps from S to E, or -1 if E
        can't be reached
    """
    # Write your code here
    pass