zoukankan      html  css  js  c++  java
  • 【LeetCode】200. 岛屿数量

    题目

    给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
    岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
    此外,你可以假设该网格的四条边均被水包围。

    示例 1:

    输入:
    11110
    11010
    11000
    00000
    输出: 1
    

    示例 2:

    输入:
    11000
    11000
    00100
    00011
    输出: 3
    

    解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。

    思路

    代码

    时间复杂度:O(row * col)
    空间复杂度:O(row * col)

    class Solution {
    public:
        int numIslands(vector<vector<char>>& grid) {
            if (grid.empty()) return 0;
            int res = 0, row = grid.size(), col = grid[0].size();
            vector<vector<bool>> visited(row, vector<bool>(col));
            for (int i = 0; i < row; ++i) {
                for (int j = 0; j < col; ++j) {
                    if (grid[i][j] == '1' && visited[i][j] == false) {
                        dfs(grid, visited, i, j);
                        ++res;
                    }                
                }
            }
            return res;
        }
    
        void dfs(vector<vector<char>> &grid, vector<vector<bool>> &visited, int i, int j) {
            int row = grid.size(), col = grid[0].size();
            if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j] == '0' || visited[i][j] == true) return;
            visited[i][j] = true;
            dfs(grid, visited, i - 1, j);
            dfs(grid, visited, i + 1, j);
            dfs(grid, visited, i, j - 1);
            dfs(grid, visited, i, j + 1);
        }
    };
    

    优化空间复杂度

    访问过就重置值为 0。

    class Solution {
    public:
        int numIslands(vector<vector<char>>& grid) {        
            if (grid.empty() || grid[0].empty()) return 0;
            int row = grid.size(), col = grid[0].size(), c = 0;
            for (int i = 0; i < row; ++i) {
                for (int j = 0; j < col; ++j) {
                    if (grid[i][j] == '1') {
                        ++c;
                        dfs(grid, i, j);
                    }                
                }
            }
            return c;
        }
        
        void dfs(vector<vector<char>>& grid, int row, int col) {        
            if (row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size() || grid[row][col] == '0') return;
            grid[row][col] = '0';
            dfs(grid, row - 1, col);
            dfs(grid, row + 1, col);
            dfs(grid, row, col - 1);
            dfs(grid, row, col + 1);
        }
    };
    
  • 相关阅读:
    js 简单getByClass得封装
    微信红包的随机算法
    js 淘宝评分
    HDU 1023 Train Problem II( 大数卡特兰 )
    HDU 1576 A/B( 逆元水 )
    HDU 5533 Dancing Stars on Me( 有趣的计算几何 )
    POJ 1664 放苹果( 递推关系 )
    HDU 2095 find your present (2)( 位运算 )
    POJ 3517 And Then There Was One( 约瑟夫环模板 )
    POJ 1988 Cube Stacking( 带权并查集 )*
  • 原文地址:https://www.cnblogs.com/galaxy-hao/p/12735852.html
Copyright © 2011-2022 走看看