LintCode 677: Number of Big Islands (经典题)

  1. Number of Big Islands
    中文English
    Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

Find the number of islands that size bigger or equal than K.

Example
Example1

Input:
[[1,1,0,0,0],[0,1,0,0,1],[0,0,0,1,1],[0,0,0,0,0],[0,0,0,0,1]]
2
Output: 2
Explanation:
the 2D grid is
[
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]
]
there are two island which size is equals to 3.
Example2

Input:
[[1,0],[0,1]]
1
Output: 2

解法1:
DFS。我用了visited数组。注意也可以不用,直接将访问过的节点清0即可。
代码如下:

class Solution {
public:
    /**
     * @param grid: a 2d boolean array
     * @param k: an integer
     * @return: the number of Islands
     */
    int numsofIsland(vector<vector<bool>> &grid, int k) {
        int nRow = grid.size();
        if (nRow == 0) return 0;
        int nCol = grid[0].size();
        visited.resize(nRow, vector<int>(nCol, 0));
        int result = 0;
        
        for (int i = 0; i < nRow; ++i) {
            for (int j = 0; j < nCol; ++j) {
                if (grid[i][j] && !visited[i][j]) {
                    amount = 0;
                    dfs(grid, i, j);
                    if (amount >= k) {
                        result++;
                    }
                }
            }
        }
        
        return result;
    }
    
private:
    void dfs(vector<vector<bool>> &grid, int i, int j) {
        if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size()) return;
        
        if (visited[i][j] || !grid[i][j]) return;
        visited[i][j] = 1;
        amount++;
        vector<int> dx = {-1, 1, 0, 0};
        vector<int> dy = {0, 0, -1, 1};
        for (int k = 0; k < 4; ++k) {
            int newX = i + dx[k];
            int newY = j + dy[k];
            dfs(grid, newX, newY);
        }
        
    }
    int amount;
    vector<vector<int>> visited;
};

解法2:BFS

解法3:Union-Find

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值