Problem Description
Given a maze represented by an m x n matrix with empty cells ('.') and walls ('+'), and a starting position (entrance), find the minimum number of steps required to reach the nearest exit from the maze. An exit is any empty cell located on the maze border (excluding the entrance itself). You can move up, down, left, or right in one step. If no exit exists, return -1.
Key Insights
- The problem requires finding the shortest path in an unweighted grid, which suggests using Breadth-First Search (BFS).
- Since all movements have the same cost, BFS guarantees the minimum steps to reach an exit.
- We need to carefully treat the entrance cell and avoid revisiting cells by marking them as visited.
- Border cells (other than the entrance) are considered valid exits.
Space and Time Complexity
Time Complexity: O(m * n) where m and n are the number of rows and columns respectively. Space Complexity: O(m * n) due to the queue and visited structure in the worst-case scenario.
Solution
We solve the problem using the Breadth-First Search (BFS) algorithm. Starting from the entrance, we systematically explore all reachable cells in layers. For each cell, we check its four possible adjacent positions (up, down, left, right). If an adjacent cell is within bounds, is not a wall, and has not been visited, we add it to the queue for further exploration. We also check if the cell is on the border (and is not the entrance) to determine if it is an exit. The first time we reach such a cell, we return the number of steps taken. If the queue is exhausted without finding an exit, we return -1.