题型:图、BFS、模拟、DFS
链接:200. 岛屿数量 - 力扣(LeetCode)
来源:LeetCode
题目描述
给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
题目样例
看起来像矩阵,但考法是图的BFS/DFS
示例 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'
题目思路
题目要求是只要有1四面为0(不要求八面,还挺人性化)就是岛屿,统计岛屿的数量
思路上可以想到遍历点,为1就看看他的四周有没有1,有就继续往下遍历——这就很有DFS的味道
C++代码
class Solution {
void DFS(vector<vector<char>>& grid ,int r,int c)//r和c来表示 要进行DFS的点的index
{
int rLen = grid.size();
int cLen = grid[0].size();
grid[r][c] = '0';//DFS会遍历到的点置0 这样碰到新的1说明是不相连的1
//模拟这个点 上、下、左、右的点的情况
if(r-1 >= 0 && grid[r-1][c] == '1') DFS(grid,r-1,c);
if(r+1 < rLen && 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 < cLen && grid[r][c+1] == '1') DFS(grid,r,c+1);
}
public:
int numIslands(vector<vector<char>>& grid) {
// 看样例感觉是矩阵类题目,结果是图类
int ans = 0;
int row = grid.size();
int column = grid[0].size();
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
{
if(grid[i][j] == '1')//深度优先搜索值为1的点
{
++ans;
DFS(grid,i,j);
}
}
return ans;
}
};