-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnearest_exit_from_entrance_in_maze.cpp
More file actions
40 lines (32 loc) · 1.14 KB
/
nearest_exit_from_entrance_in_maze.cpp
File metadata and controls
40 lines (32 loc) · 1.14 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
int m = maze.size();
int n = maze[0].size();
int sr = entrance[0];
int sc = entrance[1];
queue<pair<pair<int, int>, int>> q;
vector<vector<int>> visited(m, vector<int>(n, 0));
q.push({{sr, sc}, 0});
visited[sr][sc] = 1;
const int dr[4] = {-1, 1, 0, 0};
const int dc[4] = {0, 0, -1, 1};
while(!q.empty()){
int cr = q.front().first.first;
int cc = q.front().first.second;
int d = q.front().second;
q.pop();
if((cr != sr || cc != sc) && (cr == 0 || cr == m - 1 || cc == 0 || cc == n - 1))
return d;
for(int i = 0; i < 4; i++){
int nr = cr + dr[i];
int nc = cc + dc[i];
if(nr < 0 || nr >= m || nc < 0 || nc >= n || maze[nr][nc] == '+' || visited[nr][nc])
continue;
q.push({{nr, nc}, d + 1});
visited[nr][nc] = 1;
}
}
return -1;
}
};