class Solution {
public int countSubIslands(int[][] grid1, int[][] grid2) {
int m = grid1.length, n = grid1[0].length;
int res = 0;
for (int i = 0; i < m; i ++) {
for (int j = 0; j < n; j ++) {
if (grid1[i][j] == 0 && grid2[i][j] == 1) {
dfs(grid2, i, j);
}
}
}
for (int i = 0; i < m; i ++) {
for (int j = 0; j < n; j ++) {
if (grid2[i][j] == 1) {
res ++;
dfs(grid2, i, j);
}
}
}
return res;
}
void dfs(int[][] grad, int i, int j) {
int m = grad.length, n = grad[0].length;
if (i < 0 || j < 0 || i >= m || j >= n) return;
if (grad[i][j] == 0) return;
grad[i][j] = 0;
dfs(grad, i - 1, j);
dfs(grad, i + 1, j);
dfs(grad, i, j - 1);
dfs(grad, i, j + 1);
}
}
1905子岛屿的数量
最新推荐文章于 2024-10-30 11:20:30 发布