代码:
cpp
//岛屿题目的思想:二维矩阵图的DFS就是,上下左右遍历如果是0或者出界的话就return
//规定的是陆地上下左右是水的话它就是岛屿。当遍历矩阵图中每一个点,
//在调用递归算法之前结果加1,递归算法每次会把一个岛屿全部淹没
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
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(vector<vector<char>>& grid,int i,int j){
//出界了return
if(i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size()){
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);
}
};