此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:
grid = [
[“1”,“1”,“1”,“1”,“0”],
[“1”,“1”,“0”,“1”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“0”,“0”,“0”]
]
输出:1
示例 2:
输入:
grid = [
[“1”,“1”,“0”,“0”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“1”,“0”,“0”],
[“0”,“0”,“0”,“1”,“1”]
]
输出:3
提示:
方法:深度优先遍历(递归)
思路:
代码
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
int islandCount = 0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(grid[i][j]=='1'){
++islandCount;
dfs(grid,i,j);
}
}
}
return islandCount;
}
private:
void dfs(vector<vector<char>>& grid, int i,int j){
int rows = grid.size();
int cols = grid[0].size();
grid[i][j] = '0';//将遍历到的每个陆地均置为0
//以该陆地为起点,递归遍历上下左右的位置,如果是陆地,那表明陆地是连接在一块的,若为海水,则跳过
if(i-1>=0 && grid[i-1][j]=='1') dfs(grid,i-1,j);//往上走行数不小于0
if(i+1<=rows-1 && grid[i+1][j]=='1') dfs(grid,i+1,j);//往下走行数不大于row-1
if(j-1>=0 && grid[i][j-1]=='1') dfs(grid,i,j-1);//往左走列数不小于0
if(j+1<=cols-1 && grid[i][j+1]=='1') dfs(grid,i,j+1);//往右走列数不大于cols-1
}
};