-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode1391.cpp
More file actions
56 lines (44 loc) · 1.49 KB
/
leetcode1391.cpp
File metadata and controls
56 lines (44 loc) · 1.49 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public:
bool hasValidPath(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dirs = {
{},
{0, 1, 0, -1}, // 1: right, left
{-1, 0, 1, 0}, // 2: up, down
{0, -1, 1, 0}, // 3: left, down
{0, 1, 1, 0}, // 4: right, down
{0, -1, -1, 0}, // 5: left, up
{0, 1, -1, 0} // 6: right, up
};
vector<vector<int>> vis(m, vector<int>(n, 0));
queue<pair<int,int>> q;
q.push({0, 0});
vis[0][0] = 1;
while (!q.empty()) {
auto [r, c] = q.front();
q.pop();
if (r == m - 1 && c == n - 1) return true;
int type = grid[r][c];
for (int i = 0; i < 4; i += 2) {
int nr = r + dirs[type][i];
int nc = c + dirs[type][i + 1];
if (nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc]) {
continue;
}
int nextType = grid[nr][nc];
for (int j = 0; j < 4; j += 2) {
int backR = nr + dirs[nextType][j];
int backC = nc + dirs[nextType][j + 1];
if (backR == r && backC == c) {
vis[nr][nc] = 1;
q.push({nr, nc});
break;
}
}
}
}
return false;
}
};