200 Number of Islands 岛屿的个数

Posted lina2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了200 Number of Islands 岛屿的个数相关的知识,希望对你有一定的参考价值。

给定 ‘1‘(陆地)和 ‘0‘(水)的二维网格图,计算岛屿的数量。一个岛被水包围,并且通过水平或垂直连接相邻的陆地而形成。你可以假设网格的四个边均被水包围。
示例 1:
11110
11010
11000
00000
答案: 1
示例 2:
11000
11000
00100
00011
答案: 3

详见:https://leetcode.com/problems/number-of-islands/description/

class Solution {
public:
    int numIslands(vector<vector<char> > &grid) {
        if (grid.empty() || grid[0].empty())
        {
            return 0;
        }
        int m = grid.size(), n = grid[0].size(), res = 0;
        vector<vector<bool> > visited(m, vector<bool>(n, false));
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (grid[i][j] == ‘1‘ && !visited[i][j])
                {
                    numIslandsDFS(grid, visited, i, j);
                    ++res;
                }
            }
        }
        return res;
    }
    void numIslandsDFS(vector<vector<char> > &grid, vector<vector<bool> > &visited, int x, int y) {
        if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] != ‘1‘ || visited[x][y])
        {
            return;
        }
        visited[x][y] = true;
        numIslandsDFS(grid, visited, x - 1, y);
        numIslandsDFS(grid, visited, x + 1, y);
        numIslandsDFS(grid, visited, x, y - 1);
        numIslandsDFS(grid, visited, x, y + 1);
    }
};

 

以上是关于200 Number of Islands 岛屿的个数的主要内容,如果未能解决你的问题,请参考以下文章

算法:求岛屿的数量200. Number of Islands

[LeetCode] 200. Number of Islands 岛屿的数量

LeetCode 200:Number of Islands

[刷题] 200 Number of Islands

LeetCode | 0200. Number of Islands岛屿数量Python

[LintCode] Number of Islands(岛屿个数)