[LeetCode 200] Number of Islands

本文介绍了一种使用递归算法计算二维网格地图中岛屿数量的方法。通过遍历地图,当遇到陆地时,标记并击沉该岛屿的所有部分,以此避免重复计数,最终返回岛屿总数。算法在C++实现中表现出色,运行效率高于98.78%的在线提交。

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.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 

分析 

这道题是一道很典型的递归题。我们计算island的个数,说到底其实就是计算一个island的最大能够蔓延多大,一旦我们遇到一个’1‘,就标志着遇到了一个新的island,在+1之后,我们需要把这个island蔓延的区域全部击沉(置’0‘),以免在之后的计算中重复计数。

Code

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int row = grid.size();
        if (row == 0)
            return 0;
        int sum = 0;
        int col = grid[0].size();
        for (int i = 0; i < row; i ++)
            for (int j = 0; j < col; j ++)
            {
                if (grid[i][j] == '1')
                {
                    sum ++;
                    sink(grid, i, j);
                }
            }
        
        return sum;
    }
    
    void sink(vector<vector<char>>& grid, int x, int y)
    {
        int row = grid.size();
        int col = grid[0].size();
        if (x < 0 || x >= row || y < 0 || y >= col)
            return;
        
        if (grid[x][y] == '0')
            return;
        
        grid[x][y] = '0';
        sink(grid, x - 1, y);
        sink(grid, x+1, y);
        sink(grid, x, y-1);
        sink(grid, x, y+1);
        return;
    }
};

运行效率

Runtime: 16 ms, faster than 98.78% of C++ online submissions for Number of Islands.

Memory Usage: 10.7 MB, less than 100.00% of C++ online submissions forNumber of Islands.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值