forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-if-there-is-a-valid-path-in-a-grid.cpp
46 lines (44 loc) · 1.62 KB
/
check-if-there-is-a-valid-path-in-a-grid.cpp
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
// Time: O(m * n)
// Space: O(1)
class Solution {
public:
bool hasValidPath(vector<vector<int>>& grid) {
static const pair<int, int> E = {0, 1}, S = {1, 0},
W = {0, -1}, N = {-1, 0};
static const vector<vector<pair<int, int>>> directions = {
{W, E}, {N, S},
{W, S}, {S, E},
{W, N}, {N, E}
};
for (auto [r, c] : directions.at(grid[0][0] - 1)) {
if (!(0 <= r && r < grid.size() &&
0 <= c && c < grid[0].size())) {
continue;
}
int pr = 0, pc = 0;
while (r != grid.size() - 1 || c != grid[0].size() - 1) {
bool is_found = false;
for (const auto& [dx, dy] : directions.at(grid[r][c] - 1)) {
const auto& [nr, nc] = pair(r + dx, c + dy);
if ((nr == pr && nc == pc) ||
!(0 <= nr && nr < grid.size() &&
0 <= nc && nc < grid[0].size())) {
continue;
}
const auto& dirs = directions.at(grid[nr][nc] - 1);
if (find(cbegin(dirs), cend(dirs), pair(-dx, -dy)) == cend(dirs)) {
continue;
}
tie(pr, pc, r, c) = tuple(r, c, nr, nc);
is_found = true;
break;
}
if (!is_found) {
return false;
}
}
return true;
}
return grid.size() == 1 && grid[0].size() == 1;
}
};