给你一个由 '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
思路一:DFS
c++解法
class Solution {
public:void dfs(vector<vector<char>>& grid,int i,int j,int m,int n){if(i<0 || i>=m || j<0 || j>=n || grid[i][j] == '0')return;grid[i][j] = '0';dfs(grid,i + 1,j,m,n);dfs(grid,i - 1,j,m,n);dfs(grid,i,j + 1,m,n);dfs(grid,i,j - 1,m,n);}int numIslands(vector<vector<char>>& grid) {int m = grid.size();int n = grid[0].size();int num = 0;for(int i=0;i<m;i++)for(int j=0;j<n;j++){num += grid[i][j] - '0';dfs(grid,i,j,m,n);}return num;}
};
分析:
本题为岛屿类问题,可用dfs的方式解决,深度搜索将每个遍历过的格子赋值为2即标记为已遍历,后面根据题目需要输出答案,本题是将每个岛屿遍历一遍,当到下一个未遍历的岛屿返回值加一
总结:
本题考察对dfs的应用,利用dfs每当遍历到一个未计数的岛屿则使用dfs将其设为已遍历的岛屿