Skip to content

Nearest Exit from Entrance in Maze

MediumGraphs
Decode it first. Clues, constraints, pattern and plan before any code.

A maze is a grid where "+" is a wall and "." is open floor. You stand at entrance = [row, col] (an open cell) and can step up, down, left or right onto open floor. An exit is any open cell on the border of the maze, except the entrance itself. Return the fewest steps to reach an exit, or -1 if there is none you can reach.

maze = [["+", "+", ".", "+"],
        [".", ".", ".", "+"],
        ["+", "+", "+", "."]], entrance = [1, 2]   →  1   (step up to [0, 2])
 
maze = [[".", "+"]], entrance = [0, 0]           →  -1  (the entrance does not count)

Constraints

  • 1 <= maze.length, maze[i].length <= 100
  • maze[i][j] is "+" or "."
  • entrance is an open cell inside the maze