#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
void dfs(vector<vector<char>>& grid,int i ,int j ){
// 一个函数里可不可以有两个return语句
// if(grid[i][j] == '0'){
// return
// }
//不行,这样就会出现2个出口的问题。可以用一个return语句传送2个返回值。
if(i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || 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);
}
int numIslands(vector<vector<char>>& grid) {
int count = 0;
for(int i = 0;i < grid.size();i++){
for(int j = 0;j < grid[0].size();j++){
if(grid[i][j] == '1'){
dfs(grid,i,j);
count ++;
}
}
}
return count;
}
};
int main(){
vector<vector<char>>grid = {
{'1','1','1','1','0'},
{'1','1','0','1','0'},
{'1','1','0','0','0'},
{'0','0','0','0','0'}
};
Solution solute;
cout << solute.numIslands(grid) << endl;
}
07-12
189
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-31
613
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
527
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
404
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)