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 Maze INPUT Maze (3x4 matrix): + + . + . . E + + + . EXIT Entrance [1,2] Wall (+) Empty (.) Border Exit entrance = [1, 2] maze: 3 rows x 4 cols ALGORITHM (BFS) 1 Initialize BFS Queue = [(1,2,0)] Mark entrance visited 2 Process (1,2) Check 4 directions: Up(0,2), Down(2,2), Left(1,1), Right: wall 3 Check Border Cells (0,2): border, dist=1 (2,2): not border yet 4 Found Exit! (0,2) is on border Return steps = 1 BFS Queue State: (1,2,0) --> (0,2,1) EXIT FOUND! FINAL RESULT Shortest Path Highlighted: + + EXIT (0,2) + . . START (1,2) + + + . . Output: 1 OK - Shortest path found! 1 step: (1,2) --> (0,2) Key Insight: BFS guarantees the shortest path in an unweighted graph. We start from the entrance and explore level by level. The first border cell (excluding entrance) we reach is the nearest exit. Time: O(m*n) | Space: O(m*n) for visited array and queue. TutorialsPoint - Nearest Exit from Entrance in Maze | BFS Approach
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