forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
35 lines (33 loc) · 922 Bytes
/
Solution.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
class Solution {
private final int[] dirs = {-1, 0, 1, 0, -1};
private int[][] grid1;
private int[][] grid2;
private int m;
private int n;
public int countSubIslands(int[][] grid1, int[][] grid2) {
m = grid1.length;
n = grid1[0].length;
this.grid1 = grid1;
this.grid2 = grid2;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid2[i][j] == 1) {
ans += dfs(i, j);
}
}
}
return ans;
}
private int dfs(int i, int j) {
int ok = grid1[i][j];
grid2[i][j] = 0;
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1) {
ok &= dfs(x, y);
}
}
return ok;
}
}