岛屿数量、

2023-11-26 12:26:30 浏览数 (1)

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

示例 1:

代码语言:javascript复制
输入:grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
输出:1

示例 2:

代码语言:javascript复制
输入:grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
输出:3

思路 讲述看到这一题的思路

解题方法 描述你的解题方法

复杂度 时间复杂度: 添加时间复杂度, 示例:

空间复杂度: 添加空间复杂度, 示例:

代码语言:javascript复制
class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
    int ans=0,Nh=grid.size(),Nl=grid[0].size();    

    //可递归的lamber表达式写法
    auto dfs=[&](auto & dfs,int r,int c) ->void
    {
        grid[r][c]='0';

        if (r - 1 >= 0 && grid[r-1][c] == '1') dfs(dfs, r-1, c);
        if (r   1 < Nh && grid[r 1][c] == '1') dfs(dfs, r 1, c);
        if (c - 1 >= 0 && grid[r][c-1] == '1') dfs(dfs, r, c-1);
        if (c   1 < Nl && grid[r][c 1] == '1') dfs(dfs, r, c 1);
    };

    //程序实现。一个个搜索1,并且把一的岛屿清零,然后统计岛屿
    for(int i=0;i<Nh;i  )
        for(int j=0;j<Nl;j  )
            if(grid[i][j] == '1')
                ans  ,dfs(dfs,i,j);

    return ans;
    }
};

0 人点赞