-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1254.Number-of-Closed-Islands.java
57 lines (48 loc) · 1.4 KB
/
1254.Number-of-Closed-Islands.java
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
// https://leetcode.com/problems/number-of-closed-islands/
// algorithms
// Easy (59.85%)
// Total Accepted: 5,585
// Total Submissions: 9,331
// beats 100.0% of java submissions
class Solution {
private static final int ISLAND = 0;
private static final int SEA = 1;
public int closedIsland(int[][] grid) {
int res = 0;
int row = grid.length, col = grid[0].length;
for (int i = 1; i < row - 1; i++) {
for (int j = 1; j < col - 1; j++) {
if (grid[i][j] == ISLAND) {
if (recursive(grid, i, j)) {
res++;
}
}
}
}
return res;
}
public boolean recursive(int[][] grid, int i, int j) {
int row = grid.length, col = grid[0].length;
grid[i][j] = SEA;
if (i == 0 || i == row - 1) {
return false;
}
if (j == 0 || j == col - 1) {
return false;
}
boolean res = true;
if (grid[i - 1][j] == ISLAND) {
res &= recursive(grid, i - 1, j);
}
if (grid[i + 1][j] == ISLAND) {
res &= recursive(grid, i + 1, j);
}
if (grid[i][j - 1] == ISLAND) {
res &= recursive(grid, i, j - 1);
}
if (grid[i][j + 1] == ISLAND) {
res &= recursive(grid, i, j + 1);
}
return res;
}
}