LeetCode 200-岛屿数量

一、问题

给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算网格中岛屿的数量。
岛屿总是被水包围,且每座岛屿只能由水平和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。

Example:

输入:grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
输出:1

输入:grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
输出:3

二、思路

使用深度优先搜索

  1. 定义一个深度优先搜索函数dfs(grid,i,j)。
  • 其中grid为二维网格,i为当前位置的行数,j为当前位置的列数。具体实现:
  • 将当前位置置0。从当前位置出发,判断四周是否为1,若为1,置0,递归调用dfs。
  1. 遍历二维网格,出现‘1’的位点即调用dfs函数。
  • 每个为‘1’的位点完成一次dfs,即形成一个岛屿。且属于该岛屿的位点都被置0,不会被再次计算。

(注意:‘0’ ‘1’的数据类型是char)

三、代码

class Solution {
public:
    void dfs(vector>& grid,int i,int j){
        int line=grid.size();
        int col=grid[0].size();

        grid[i][j]='0';

        if(j>0&&grid[i][j-1]=='1') {
            grid[i][j-1]='0';
            dfs(grid,i,j-1);
        }
        if(j0&&grid[i-1][j]=='1') {
            grid[i-1][j]='0';
            dfs(grid,i-1,j);
        }
        if(i>& grid) {
        if(grid.size()==0){
            return 0;
        }
        int island_num=0;
        int line=grid.size();
        int col=grid[0].size();
        for(int i=0;i

四、复杂度

  1. 时间复杂度:m*n
  2. 空间复杂度:m*n
    LeetCode 200-岛屿数量_第1张图片

你可能感兴趣的:(LeetCode 200-岛屿数量)