Nearest Exit from Entrance in Maze - Problem

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.

Input & Output

Example 1 — Basic Maze
$ Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+",".","."]], entrance = [1,2]
Output: 1
💡 Note: Start at (1,2). The nearest exit is at (1,3) which is 1 step to the right. This is a border cell.
Example 2 — No Exit Available
$ Input: maze = [["+","+","+"],[".",".","."],[".",".","."]], entrance = [1,0]
Output: -1
💡 Note: Start at (1,0). Although this is a border cell, it's the entrance so doesn't count as exit. All other border cells are walls (+), so no exit exists.
Example 3 — Multiple Paths
$ Input: maze = [[".","+"],[".","."]], entrance = [1,0]
Output: 1
💡 Note: Start at (1,0). Can go up to (0,0) in 1 step, which is a border cell and serves as an exit.

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

Visualization

Tap to expand
Nearest Exit from Entrance in MazeInput Maze++E+.S.+++..BFS Exploration012StartLevel 1Exit Found!Entrance (1,2)Exit (0,2)Result: 1 step to nearest exit
Understanding the Visualization
1
Input
Maze with walls (+), paths (.), and entrance position
2
Process
Use BFS to explore paths level by level until border reached
3
Output
Return minimum steps to reach any exit, or -1 if impossible
Key Takeaway
🎯 Key Insight: BFS guarantees shortest path by exploring all cells at distance k before distance k+1
Asked in
Google 25 Amazon 30 Microsoft 20 Facebook 15
32.4K Views
Medium Frequency
~15 min Avg. Time
867 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen