Sponsored
Sponsored
In this approach, we use the Breadth-First Search (BFS) algorithm to explore the maze. BFS is suitable because it explores nodes layer by layer, ensuring that the shortest path is found. We initialize a queue with the entrance cell and explore its neighbors (up, down, left, right). If a neighbor is an unvisited empty cell and is on the boundary (except the entrance), it can be considered as an exit.
Each time we explore a cell, we mark it as visited by changing its state to '+'. This prevents revisiting nodes, which ensures that we won't traverse the same path multiple times. We keep track of steps taken from the entrance to the current cell, and if we reach an exit, we return the number of steps. If the queue is exhausted without finding an exit, we return -1.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns in the maze. In the worst case, all cells are traversed.
Space Complexity: O(m * n) for the queue used in BFS.
1#include <vector>
2#include <queue>
3#include <utility>
4using namespace std;
5
6class Solution {
7public:
8 int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
9 int m = maze.size(), n = maze[0].size();
10 queue<pair<int, int>> q;
11 q.push({entrance[0], entrance[1]});
12 maze[entrance[0]][entrance[1]] = '+';
13 int directions[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
14 int steps = 0;
while (!q.empty()) {
int q_size = q.size();
steps++;
for (int i = 0; i < q_size; ++i) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int d = 0; d < 4; ++d) {
int nx = x + directions[d][0];
int ny = y + directions[d][1];
if (nx >= 0 && ny >= 0 && nx < m && ny < n && maze[nx][ny] == '.') {
if (nx == 0 || ny == 0 || nx == m - 1 || ny == n - 1) {
return steps;
}
maze[nx][ny] = '+';
q.push({nx, ny});
}
}
}
}
return -1;
}
};
The C++ BFS implementation also starts by queuing the entrance and marking it as visited. We use a queue to process cells. From each cell, all possible directions are explored. If an unvisited neighbor is at the boundary, it returns the number of steps as it's an exit. The use of pairs aids in handling cell coordinates efficiently.
In this approach, we use the Depth-First Search (DFS) algorithm to explore the maze. DFS might not be as efficient as BFS for finding the shortest path, but for educational purposes, it demonstrates another way to traverse the maze. We recursively explore each path, marking cells as visited and backtracking when dead-ends or exits are encountered.
This approach keeps a global minimum step count, updating it whenever an exit (that isn't the entrance) is found. Through recursive calls, each possible path is explored until all directions are exhausted. The main objective is to identify the closest exit with respect to steps taken from the entrance cell.
Time Complexity: O((m * n)^2) in the worst case, where m and n are dimensions of the maze.
Space Complexity: O(m * n) due to recursion stack usage in deep recursive path exploration.
1var nearestExit = function(maze, entrance) {
2 let minSteps = Infinity;
3 const directions = [[0,1],[1,0],[0,-1],[-1,0]];
4
5 function dfs(x, y, steps) {
6 const m = maze.length, n = maze[0].length;
7 if (x < 0 || y < 0 || x >= m || y >= n || maze[x][y] !== '.') return;
8 if ((x === 0 || y === 0 || x === m - 1 || y === n - 1) && steps !== 0) {
9 minSteps = Math.min(minSteps, steps);
10 }
11 maze[x][y] = '+'; // mark as visited
12 for (const [dx, dy] of directions) {
13 dfs(x + dx, y + dy, steps + 1);
14 }
15 maze[x][y] = '.'; // backtrack
16 }
17 dfs(entrance[0], entrance[1], 0);
18 return minSteps === Infinity ? -1 : minSteps;
19};
JavaScript's DFS recurses through potential paths from a starting cell, considering all valid moves, and keeping a count of steps. The function adjusts to ensure exits are marked and paths are revisitable, allowing full grid searches for optimum and correct solutions.