Skip to content

Commit 6aede80

Browse files
authored
Create 1568. Minimum Number of Days to Disconnect Island (#554)
2 parents 530688f + 724e60a commit 6aede80

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
class Solution {
2+
public:
3+
int minDays(vector<vector<int>>& grid) {
4+
if (isDisconnected(grid)) return 0;
5+
6+
int m = grid.size();
7+
int n = grid[0].size();
8+
9+
// Try removing one cell
10+
for (int i = 0; i < m; ++i) {
11+
for (int j = 0; j < n; ++j) {
12+
if (grid[i][j] == 1) {
13+
grid[i][j] = 0;
14+
if (isDisconnected(grid)) return 1;
15+
grid[i][j] = 1;
16+
}
17+
}
18+
}
19+
20+
// Try removing two cells
21+
for (int i = 0; i < m; ++i) {
22+
for (int j = 0; j < n; ++j) {
23+
if (grid[i][j] == 1) {
24+
grid[i][j] = 0;
25+
for (int x = 0; x < m; ++x) {
26+
for (int y = 0; y < n; ++y) {
27+
if (grid[x][y] == 1) {
28+
grid[x][y] = 0;
29+
if (isDisconnected(grid)) return 2;
30+
grid[x][y] = 1;
31+
}
32+
}
33+
}
34+
grid[i][j] = 1;
35+
}
36+
}
37+
}
38+
return 2;
39+
}
40+
41+
private:
42+
bool isDisconnected(vector<vector<int>>& grid) {
43+
int m = grid.size();
44+
int n = grid[0].size();
45+
vector<vector<int>> visited(m, vector<int>(n, 0));
46+
47+
int landCount = 0;
48+
for (int i = 0; i < m; ++i) {
49+
for (int j = 0; j < n; ++j) {
50+
if (grid[i][j] == 1) {
51+
++landCount;
52+
if (!visited[i][j]) {
53+
if (landCount > 1) return true;
54+
bfs(grid, visited, i, j);
55+
}
56+
}
57+
}
58+
}
59+
return landCount == 0;
60+
}
61+
62+
void bfs(vector<vector<int>>& grid, vector<vector<int>>& visited, int i, int j) {
63+
int m = grid.size();
64+
int n = grid[0].size();
65+
queue<pair<int, int>> q;
66+
q.push({i, j});
67+
visited[i][j] = 1;
68+
69+
vector<int> dirX = {-1, 1, 0, 0};
70+
vector<int> dirY = {0, 0, -1, 1};
71+
72+
while (!q.empty()) {
73+
auto [x, y] = q.front();
74+
q.pop();
75+
76+
for (int d = 0; d < 4; ++d) {
77+
int newX = x + dirX[d];
78+
int newY = y + dirY[d];
79+
if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == 1 && !visited[newX][newY]) {
80+
visited[newX][newY] = 1;
81+
q.push({newX, newY});
82+
}
83+
}
84+
}
85+
}
86+
};

0 commit comments

Comments
 (0)