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;
}; 

 

转载于:https://www.cnblogs.com/heyn1/p/10996386.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值