zoukankan      html  css  js  c++  java
  • [LintCode] Number of Islands 岛屿的数量

    Given a boolean 2D matrix, find the number of islands.

     Notice

    0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

    Example

    Given graph:

    [
      [1, 1, 0, 0, 0],
      [0, 1, 0, 0, 1],
      [0, 0, 0, 1, 1],
      [0, 0, 0, 0, 0],
      [0, 0, 0, 0, 1]
    ]
    

    return 3.

    LeetCode上的原题,请参见我之前的博客Number of Islands

    class Solution {
    public:
        /**
         * @param grid a boolean 2D matrix
         * @return an integer
         */
        int numIslands(vector<vector<bool>>& 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] && !visited[i][j]) {
                        helper(grid, visited, i, j);
                        ++res;
                    }
                }
            }
            return res;
        }
        void helper(vector<vector<bool>>& grid, vector<vector<bool>>& visited, int i, int j) {
            int m = grid.size(), n = grid[0].size();
            if (i < 0 || i >= m || j < 0 || j >= n || !grid[i][j] || visited[i][j]) return;
            visited[i][j] = true;
            helper(grid, visited, i + 1, j);
            helper(grid, visited, i - 1, j);
            helper(grid, visited, i, j + 1);
            helper(grid, visited, i, j - 1);
        }
    };
  • 相关阅读:
    为zabbix穿上一件漂亮的外衣
    CentOS7 Ceph分布式集群部署
    SSH 免秘钥登录
    zabbix监控Tomcat/JVM 实例性能
    zabbix 监控 IPMI
    2装饰者模式
    1代理模式
    3单例模式
    2抽象工厂模式
    1工厂模式
  • 原文地址:https://www.cnblogs.com/grandyang/p/5672890.html
Copyright © 2011-2022 走看看