zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    Linux命令——find
    Linux命令——locate
    python模块:datetime
    python模块:json
    python模块:shelve
    python模块:shutil
    python模块:sys
    python:OS模块
    str.index()与str.find()比较
    python模块:re
  • 原文地址:https://www.cnblogs.com/immjc/p/7645106.html
Copyright © 2011-2022 走看看