Nearest Exit from Entrance in Maze

You are given an m x n matrix maze (0-indexed) with empty cells represented as '.' and walls represented as '+'. You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.

In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze.

Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.

Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.

Example 1
+ + . +
. . . +
+ + + .
Inputmaze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output1
The exits are [1,0], [0,2], and [2,3], and the nearest reachable exit is [0,2], which is 1 step away from the entrance.
Example 2
+ + +
. . .
+ + +
Inputmaze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
Output2
The entrance [1,0] does not count as an exit, and the nearest exit is [1,2], which is 2 steps to the right.

Constraints

  • maze.length == m
  • maze[i].length == n
  • 1 <= m, n <= 100
  • maze[i][j] is either '.' or '+'.
  • entrance.length == 2
  • 0 <= entrancerow < m
  • 0 <= entrancecol < n
  • entrance will always be an empty cell.

Asked at 9 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate