(岛屿问题二) leetcode 200: 岛屿数量

leetcode 200: 岛屿数量

在做本题目之前,请先看前一篇文章。链接:link

题目描述

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

Input:grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
  ]
Output:1

示例二:

Input:grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
  ]
Output:3

题解思路

根据题目要找网格中岛屿的数量,跟第一道题目:求岛屿的最大面积基本类似。从一个位置开始,先进行深度优先搜索,把跟该位置相连的所有的陆地全部搜索完,搜索过的位置将其元素进行更改,避免重复搜索。然后再从其他位置进行搜索,看有没有其他跟上述陆地完全没有联系的新的陆地,再进行深度优先搜索,把跟该位置相连的所有的陆地全部搜索完。不断重复该过程。每搜索完一片陆地后将计数值加 1 1 1

代码

    int numIslands(vector<vector<char>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        if(m == 0 || n == 0) return 0;
        int count = 0;
        for(int i=0; i<m; ++i)
        {
            for(int j=0; j<n; ++j)
            {
                if(grid[i][j] == '1')
                {
                    count++;
                    dfs(i, j, grid);    
                }
            }
        }
        return count;
    }
    vector<int> direction{0,1,0,-1,0};
    void dfs(int i, int j, vector<vector<char>> & grid)
    {
        if(i < 0 || i>= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] == '0')
        {
            return;
        }
        if(grid[i][j] == '1')
        {
            grid[i][j] = '0';
        }
        for(int dk=0; dk < 4; ++dk)
        {
            int x = i + direction[dk];
            int y = j + direction[dk+1];
            dfs(x, y, grid);
        }
    }

你可能感兴趣的:(leetcode数组专栏,算法,leetcode,dfs,c++)