-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1568-days-disconnect-island.dart
94 lines (79 loc) · 1.94 KB
/
1568-days-disconnect-island.dart
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class Solution {
final List<List<int>> directions = [
[-1, 0], // up
[1, 0], // down
[0, -1], // left
[0, 1] // right
];
int minDays(List<List<int>> grid) {
if (countIslands(grid) != 1) return 0;
int m = grid.length;
int n = grid[0].length;
//check
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
grid[i][j] = 0; // remove
if (countIslands(grid) != 1) return 1;
grid[i][j] = 1; // restore
}
}
}
// can't disconnect with one cell, need 2 days
return 2;
}
int countIslands(List<List<int>> grid) {
int m = grid.length;
int n = grid[0].length;
List<List<bool>> visited = List.generate(m, (_) => List.filled(n, false));
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1 && !visited[i][j]) {
dfs(grid, i, j, visited);
count++;
}
}
}
return count;
}
void dfs(List<List<int>> grid, int row, int col, List<List<bool>> visited) {
int m = grid.length;
int n = grid[0].length;
visited[row][col] = true;
for (var dir in directions) {
int newRow = row + dir[0];
int newCol = col + dir[1];
if (newRow >= 0 &&
newRow < m &&
newCol >= 0 &&
newCol < n &&
grid[newRow][newCol] == 1 &&
!visited[newRow][newCol]) {
dfs(grid, newRow, newCol, visited);
}
}
}
}
void main() {
final solution = Solution();
// Example 1
final grid1 = [
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
];
print('Example 1: ${solution.minDays(grid1)}'); // Output: 2
// Example 2
final grid2 = [
[1, 1]
];
print('Example 2: ${solution.minDays(grid2)}'); // Output: 2
// Example 3
final grid3 = [
[1, 1, 0],
[1, 1, 0],
[0, 0, 0]
];
print('Example 3: ${solution.minDays(grid3)}'); // Output: 1
}