整体架构还是岛屿问题的基础架构
步骤:
- 子岛屿的存在和grid1有关,在grid2中的陆地若在grid1中对应的位置为海,则说明该陆地不属于子岛屿,便使用DFS方法直接淹没即可
- grid2中剩下的岛屿就是子岛屿了,直接套用框架中统计子岛屿即可
class Solution {
public int countSubIslands(int[][] grid1, int[][] grid2) {
int res = 0;
int m = grid1.length;
int n = grid1[0].length;
for(int i = 0;i<m;i++){
for(int j = 0;j<n;j++){
if(grid2[i][j] == 1&&grid1[i][j] == 0){
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[][] grid,int i,int j){
int m = grid.length;
int n = grid[0].length;
if(i<0||j<0||i>=m||j>=n){
return;
}
if(grid[i][j] == 0){
return;
}
grid[i][j] = 0;
DFS(grid,i+1,j);
DFS(grid,i-1,j);
DFS(grid,i,j+1);
DFS(grid,i,j-1);
}
}