[LeetCode] Nearest Exit from Entrance in Maze

1926. Nearest Exit from Entrance in Maze

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int nearestExit(vector<vector<char>>& maze, vector<int>& e) {
int dx[4]{0, 1, 0, -1}, dy[4]{-1,0,1,0}, n(maze.size()), m(maze[0].size()), res(0);
queue<pair<int, int>> q;
maze[e[0]][e[1]] = '+';
q.push({e[0], e[1]});
while(!q.empty()) {
++res;
int sz = q.size();
while(sz--) {
auto pos = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int ny(pos.first + dy[i]), nx(pos.second + dx[i]);
if(0 <= nx && nx < m && 0 <= ny && ny < n && maze[ny][nx] == '.') {
if(nx == 0 || ny == 0 || nx == m-1 || ny == n-1) return res;
q.push({ny, nx});
maze[ny][nx] = '+';
}
}
}
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/13/PS/LeetCode/nearest-exit-from-entrance-in-maze/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.