思路:利用深度优先搜索的思路来查找1身边的1,并且遍历之后进行0替换防止重复dfs,代码如下所示
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int row = grid.size();
int col = grid[0].size();
int numoflands = 0;
//从第一行开始遍历,是岛屿则进行周围深度优先搜索
for(int r = 0;r < row;r++){
for(int c = 0;c < col;c++){
if(grid[r][c] == '1'){
++numoflands;
dfs(grid,r,c);
}
}
}
return numoflands;
}
//dfs用于消除“1”旁边的“1”并用“0”替换掉防止二次遍历
void dfs(vector<vector<char>>& grid,int r,int c){
int nr = grid.size();
int nc = grid[0].size();
grid[r][c] = '0';//用“0”替换“1”,防止重复调用
if(r-1>=0&&grid[r-1][c] == '1') dfs(grid,r-1,c);
if(r+1<nr&&grid[r+1][c] == '1') dfs(grid,r+1,c);
if(c-1>=0&&grid[r][c-1] == '1') dfs(grid,r,c-1);
if(c+1<nc&&grid[r][c+1] == '1') dfs(grid,r,c+1);
}
};