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;
    }; 
  • 相关阅读:
    Java 开发环境配置
    kettle脚本定时任务不执行
    python 列表之队列
    tensorflow训练过程中内存溢出
    关于 numpy.array和list之间的转换
    vscode 小笔记
    【python2/3坑】从gensim的Word2Vec.load()的中文vector模型输出时显示unicode码
    WingIDE用法笔记
    numpy.ndarray类型的数组元素输出时,保留小数点后4位
    tensorboard 用法
  • 原文地址:https://www.cnblogs.com/heyn1/p/10996386.html
Copyright © 2011-2022 走看看