public int countSubIslands(int[][] grid1, int[][] grid2) {
int m = grid1.length, n = grid1[0].length, count = 0;
// 先排除不是子岛屿的节点
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, m, n);
}
}
}
System.out.println("======");
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
// 对于条件case1和case2来说
// 这块可以优化成if(grid2[i][j] == 1)
if(grid2[i][j] == 1 && grid1[i][j] == 1){
count++;
dfs(grid2, i, j, m, n);
}
}
}
return count;
}
public void dfs(int[][] grid, int i, int j, int m, int n){
if(i >= m || i < 0 || j >= n || j < 0
|| grid[i][j] == 0 ){
return;
}
grid[i][j] = 0;
dfs(grid, i + 1, j, m, n);
dfs(grid, i - 1, j, m, n);
dfs(grid, i, j + 1, m, n);
dfs(grid, i, j - 1, m, n);
}
public static void main(String[] args) {
int[][] grid1 = {{1,1,1,0,0},{0,1,1,1,1},{0,0,0,0,0},{1,0,0,0,0},{1,1,0,1,1}};
int[][] grid2 = {{1,1,1,0,0},{0,0,1,1,1},{0,1,0,0,0},{1,0,1,1,0},{0,1,0,1,0}};
CountSubIslands countSubIslands = new CountSubIslands();
countSubIslands.countSubIslands(grid1, grid2);
}