95. Shortest way through a maze
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
Sand oneE. SandEare 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
maze = ["S..",
".#.",
"..E"]4Example 2
maze = ["S#E"]-1Example 3
maze = ["SE"]1Constraints
mazehas 1 to 20 rows of 1 to 20 characters each, all the same length, made ofS,E,#and..
Submit also runs 8 more tests you can't see.
Practises Modules and Imports (lesson 22).
- First find the
(row, column)ofSand ofE. Keep a dictionary from each cell reached to its number of steps, starting with{start: 0}. collections.dequeis a queue:append()adds at the back andpopleft()takes from the front, so cells come out in the order they were reached, nearest first.- Take a cell from the front; if it is
E, return its steps. Otherwise add each open neighbour not reached yet, with one step more. If the queue empties, return -1.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.