-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminDays.java
More file actions
61 lines (51 loc) · 1.73 KB
/
minDays.java
File metadata and controls
61 lines (51 loc) · 1.73 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
52
53
54
55
56
57
58
59
60
61
class Solution {
public int minDays(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
// Step 1: Check if the grid is already disconnected
if (countIslands(grid) != 1) {
return 0;
}
// Step 2: Try removing one land cell and check if the grid becomes disconnected
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
grid[i][j] = 0; // Temporarily set to water
if (countIslands(grid) != 1) {
return 1;
}
grid[i][j] = 1; // Revert back to land
}
}
}
// Step 3: If not, return 2
return 2;
}
private int countIslands(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
boolean[][] visited = new boolean[m][n];
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, visited, i, j);
count++;
}
}
}
return count;
}
private void dfs(int[][] grid, boolean[][] visited, int i, int j) {
int m = grid.length;
int n = grid[0].length;
if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0 || visited[i][j]) {
return;
}
visited[i][j] = true;
dfs(grid, visited, i + 1, j);
dfs(grid, visited, i - 1, j);
dfs(grid, visited, i, j + 1);
dfs(grid, visited, i, j - 1);
}
}