给你一个由 '1'(陆地)和 '0'(水)组成的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 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
提示:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] 的值为 '0' 或 '1'
方法:深度优先遍历(递归)
思路:
- 顺序遍历每一个网格,
- 如果是0,跳过;
- 如果是1,则为岛屿,岛屿总数+1。
考虑到陆地可能相连的情况,因此需要将相连接的陆地识别为一块岛屿。由于如果是陆地的话,我们的遍历的过程中即跳过。因此我们以当前遍历到的陆地为起点,递归遍历该陆地的上下左右(所有连在一起的节点),并将遍历到的陆地置为0。 - 依次递归每一个网格
- 遍历所有网格
代码
cpp
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
}
};