问题描述:
解题思路:
遍历二位数组,找到‘1’的陆地,采用dfs广度优先遍历改点上下左右所有的点,将‘1’的陆地全部淹没成‘0’,该点向四周扩散,直到扩散到该点周围没有陆地了终止,记作一个岛屿。以此类推。
题解:
class Solution {
public int numIslands(char[][] grid) {
int m = grid.length;
int n = grid[0].length;
int res = 0;
for(int i = 0;i<m;i++){
for(int j = 0;j<n;j++){
if(grid[i][j] == '1'){
res ++;
dfs(grid,i,j);
}
}
}
return res;
}
void dfs(char[][] 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,j+1);
dfs(grid,i-1,j);
dfs(grid,i,j-1);
}
}