Editor

Escape the Maze

#105 · Graphs · Intermediate · 85 XP · about 15 min

A maze is a list of strings of equal length. 'S' is where you start, 'E' is the exit, '#' is a wall and '.' is open floor. Each step moves you one square up, down, left or right, never into a wall and never off the edge. Write escape_steps(maze) that returns the smallest number of steps needed to reach the exit, or -1 if the exit cannot be reached.

Examples

maze = [
    'S.#.',
    '..#E',
    '#...',
    '....',
]
escape_steps(maze)  # returns 6
escape_steps(['S#E'])  # returns -1
escape_steps(['SE'])  # returns 1

In the first maze the wall in the third column is in the way, so you walk down to the third row, across, and back up to the exit: 6 steps.

Constraints

  • 1 to 50 rows, each with 1 to 50 characters.
  • There is exactly one 'S' and exactly one 'E'.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.