[LeetCode] Number of Islands

Posted immjc

tags:

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

Given a 2d grid map of ‘1‘s (land) and ‘0‘s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

寻找岛屿的个数。核心思想是利用一个visited二维数组来标志一个数(1)是否被访问过。在grid二维数组中局部使用广度优先遍历来判断并寻找岛屿。如果访问过则下次就不用将其再次计算。

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty() || grid[0].empty())
            return 0;
        int cnt = 0;
        const int M = grid.size();
        const int N = grid[0].size();
        vector<vector<bool>> visited(M, vector<bool>(N, false));
        for (int i = 0; i != M; i++) {
            for (int j = 0; j != N; j++) {
                if (!visited[i][j] && grid[i][j] == 1) {
                    numIslandsCore(grid, visited, i, j);
                    cnt++;
                }
            }
        }
        return cnt;
    }
    
    void numIslandsCore(vector<vector<char>>& grid, vector<vector<bool>>& visited, int i, int j) {
        if (i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && !visited[i][j] && grid[i][j] == 1) {
            visited[i][j] = true;
            numIslandsCore(grid, visited, i - 1, j);
            numIslandsCore(grid, visited, i, j - 1);
            numIslandsCore(grid, visited, i, j + 1);
            numIslandsCore(grid, visited, i + 1, j);
        }
    }
};
// 6 ms

 







以上是关于[LeetCode] Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(191):Number of 1 Bits

[LeetCode]Number of 1 Bits

Leetcode 200. Number of Islands

LeetCode 191. Number of 1 Bits

LeetCode191 Number of 1 Bits. LeetCode231 Power of Two. LeetCode342 Power of Four

python 学习 leetcode ---number of island