Nearest Exit from Entrance in Maze

You are given an `m x n` matrix `maze` (0-indexed) with empty cells `'.'` and walls `'+'`, and the `entrance` of the maze, where `entrance = [entrance_row, entrance_col]` is the cell you start in. In one step you can move up, down, left or right, but not into a wall or outside the maze. Find the nearest exit: an empty cell on the border of the maze. The entrance does not count as an exit. Return the number of steps on the shortest path from the entrance to the nearest exit, or `-1` if no such path exists.

30:00

Nearest Exit from Entrance in Maze
medium
Free written solution
Topics
Companies

You are given an m x n matrix maze (0-indexed) with empty cells '.' and walls '+', and the entrance of the maze, where entrance = [entrance_row, entrance_col] is the cell you start in. In one step you can move up, down, left or right, but not into a wall or outside the maze. Find the nearest exit: an empty cell on the border of the maze. The entrance does not count as an exit. Return the number of steps on the shortest path from the entrance to the nearest exit, or -1 if no such path exists.

Example 1:
Input: {"maze":[["+","+",".","+"],[".",".",".","+"],["+","+","+","."]],"entrance":[1,2]}
Output: 1
Constraints:
  • maze.length==m\text{maze.length} == m

  • maze[i].length==n\text{maze}[i].\text{length} == n

  • 1≤m,n≤1001 \leq m, n \leq 100

  • maze[i][j]\text{maze}[i][j] is either '.' or '+'

  • entrance.length==2\text{entrance.length} == 2

  • 0≤entrance_row<m0 \leq \text{entrance\_row} < m

  • 0≤entrance_col<n0 \leq \text{entrance\_col} < n

  • entrance will always be an empty cell

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"maze":[["+","+",".","+"],[".",".",".","+"],["+","+","+","."]],"entrance":[1,2]}

The exits are the 3 open border cells (dashed), not counting the entrance. Some may be walled off. BFS finds the closest one it can actually reach.

steps

0

queue

1

answer

...

E

entrance

wall

reached, number = steps

possible exit

route to nearest exit

Variables
VariableValue
m3
n4
exits3
DepthFunction Call
Stack empty
0/3