-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0980.cpp
More file actions
51 lines (43 loc) · 1.44 KB
/
Copy path0980.cpp
File metadata and controls
51 lines (43 loc) · 1.44 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
class Solution {
vector<pair<int, int>> offset = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int m, n;
bool valid(int x, int y) { return x >= 0 && x < m && y >= 0 && y < n; }
int find(vector<vector<int>> &grid, int x, int y, int obs) {
stack<pair<int, int>> st;
st.push({x, y});
int count = 0, goal = m * n - obs - 1, crnt = 0;
while (!st.empty()) {
auto p = st.top();
if (grid[p.first][p.second] == 3) {
st.pop();
grid[p.first][p.second] = 0;
crnt--;
continue;
}
grid[p.first][p.second] = 3;
crnt++;
for (auto &o : offset) {
int x = p.first + o.first;
int y = p.second + o.second;
if (!valid(x, y) || grid[x][y] == 3 || grid[x][y] == -1) continue;
if (grid[x][y] == 2)
count += crnt == goal;
else
st.push({x, y});
}
}
return count;
}
public:
int uniquePathsIII(vector<vector<int>> &grid) {
m = grid.size(), n = grid[0].size();
int x, y, count = 0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (grid[i][j] == 1)
x = i, y = j;
else if (grid[i][j] == -1)
count++;
return find(grid, x, y, count);
}
};