Nearest Exit from Entrance in Maze
The key idea
BFS from the entrance explores cells in order of distance, so the FIRST border empty cell it reaches (other than the entrance itself) is by definition the nearest exit. Mark cells visited as you enqueue them to keep each cell on the queue at most once.
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.
Constraints
maze.length == mmaze[i].length == n1 <= m, n <= 100maze[i][j]is either.or+entrance.length == 20 <= entrancerow < m0 <= entrancecol < nentrancewill always be an empty cell.
Examples
Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
Output: 2
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output: 1
Input: maze = [[".","+"]], entrance = [0,0]
Output: -1
Complexity
Time: O(m * n) Space: O(m * n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More BFS / DFS problems
- 01 MatrixMEDIUM
- Average of Levels in Binary TreeEASY
- Binary Tree Level Order TraversalMEDIUM
- Binary Tree Level Order Traversal IIMEDIUM
- Binary Tree Right Side ViewMEDIUM
- Binary Tree Zigzag Level Order TraversalMEDIUM
- Find Bottom Left Tree ValueMEDIUM
- Find Largest Value in Each Tree RowMEDIUM
- Flood FillEASY
- Keys and RoomsMEDIUM
- Max Area of IslandMEDIUM
- Maximum Level Sum of a Binary TreeMEDIUM