zoukankan      html  css  js  c++  java
  • LeetCode-200 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.

    题目大意

    给定一个二维数组(数组元素只有‘1’和‘0’),计算其中有几个相邻的‘1’的群落的个数(相邻的‘1’即为上、下、左、右中有‘1’相邻则将其视为一个‘1’的群落)。

    示例

    E1

    Input:
    11110
    11010
    11000
    00000
    
    Output: 1

    E2

    Input:
    11000
    11000
    00100
    00011
    
    Output: 3

    解题思路

    遍历一遍二维数组,遇到‘1’将在该位置展开DFS将相邻的所有的‘1’设置为‘0’。

    复杂度分析

    时间复杂度:O(n)

    空间复杂度:O(1)

    代码

    class Solution {
    public:
        int numIslands(vector<vector<char>>& grid) {
            m = grid.size();
            if(m == 0)
                return 0;
            n = grid[0].size();
            
            int res = 0;
            //遍历grid,查找‘1’的个数,该个数即为答案,因为查找到一个之后会DFS将相邻    
            //的‘1’设为‘0’
            for(int i = 0; i < m; i++) {
                for(int j = 0; j < n; j++) {
                    if(grid[i][j] == '1') {
                        ++res;
                        dfs(grid, i, j);
                    }
                }
            }
            
            return res;
        }
        
        //进行DFS将相邻的‘1’设置为‘0’,包括该位置本身
        void dfs(vector<vector<char> >& grid, int x, int y) {
            grid[x][y] = '0';
            for(int i = 0; i < 4; i++) {
                int nx = x + dir[i][0], ny = y + dir[i][1];
                if(nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == '1') {
                    dfs(grid, nx, ny);
                }
            }
        }
        
    private:
        //保存四个方向,便于DFS时进行方向遍历
        int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
        int m, n;
    }; 
  • 相关阅读:
    思考题
    对敏捷开发的见解
    Code Review(自评)
    求数组最大子数组和
    [ASP.NET]在虚拟目录中禁止web.config继承IIS根目录的web.config的配置
    客户的真实需求
    利用using和try/finally語句來清理資源.
    《代码整洁之道》简单总结
    ASP.NET页面级别的事
    根据DIV移动生成图片
  • 原文地址:https://www.cnblogs.com/heyn1/p/10996386.html
Copyright © 2011-2022 走看看