-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1568.cpp
More file actions
51 lines (49 loc) · 1.53 KB
/
1568.cpp
File metadata and controls
51 lines (49 loc) · 1.53 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 {
public:
vector<pair<int, int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
void dfs(vector<vector<int>>& grid, int x, int y, int m, int n) {
grid[x][y] = -1;
for (auto& direction : directions) {
int xx = x + direction.first;
int yy = y + direction.second;
if (xx < 0 || xx >= m || yy < 0 || yy >= n) continue;
if (grid[xx][yy] != 1) continue;
dfs(grid, xx, yy, m, n);
}
}
bool isNotConnected(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int count = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
dfs(grid, i, j, m, n);
count++;
}
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == -1) {
grid[i][j] = 1;
}
}
}
return count >= 2 || count == 0;
}
int minDays(vector<vector<int>>& grid) {
if (isNotConnected(grid)) return 0;
int m = grid.size();
int n = grid[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) continue;
grid[i][j] = 0;
if (isNotConnected(grid)) return 1;
grid[i][j] = 1;
}
}
return 2;
}
};