-
Notifications
You must be signed in to change notification settings - Fork 3
/
2556.cpp
59 lines (56 loc) · 1.73 KB
/
2556.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
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public:
bool isPossibleToCutPath(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
queue<pair<int, int>> q;
q.push({m - 1, n - 1});
visited[m - 1][n - 1] = true;
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
if (x - 1 >= 0 && visited[x - 1][y] == false && grid[x - 1][y]) {
q.push({x - 1, y});
visited[x - 1][y] = true;
}
if (y - 1 >= 0 && visited[x][y - 1] == false && grid[x][y - 1]) {
q.push({x, y - 1});
visited[x][y - 1] = true;
}
}
if (visited[0][0] == false) return true;
unordered_set<int> st;
// right -> down
int x = 0;
int y = 0;
while (x != m - 1 || y != n - 1) {
if (y + 1 < n && visited[x][y + 1]) {
y += 1;
if (x != m - 1 || y != n - 1) {
st.insert(x * n + y);
}
}
else if (x + 1 < m && visited[x + 1][y]){
x += 1;
if (x != m - 1 || y != n - 1) {
st.insert(x * n + y);
}
}
}
// down -> right
x = 0;
y = 0;
while (x != m - 1 || y != n - 1) {
if (x + 1 < m && visited[x + 1][y]) {
x += 1;
if (st.count(x * n + y)) return true;
}
else if (y + 1 < n && visited[x][y + 1]) {
y += 1;
if (st.count(x * n + y)) return true;
}
}
return false;
}
};