LintCode 434.岛屿的个数Ⅱ

给定 n, m, 分别代表一个二维矩阵的行数和列数, 并给定一个大小为 k 的二元数组A. 初始二维矩阵全0. 二元数组A内的k个元素代表k次操作, 设第i个元素为 (A[i].x, A[i].y), 表示把二维矩阵中下标为A[i].x行A[i].y列的元素由海洋变为岛屿. 问在每次操作之后, 二维矩阵中岛屿的数量. 你需要返回一个大小为k的数组.

并查集
把每个陆地看作一个集合 当新添加的元素上下左右有陆地并且它们不在一个集合 把它们合并为一个集合
每新创建一个陆地 至多会增加一个岛屿 每遇到一个不在同一集合的陆地 岛屿数量就会减1

public class Solution {
    /**
     * @param n: An integer
     * @param m: An integer
     * @param operators: an array of point
     * @return: an integer array
     */
    private int[] father = null;
    private int[] isLand = null;
    int count = 0;
    public int find(int a){
        if(father[a] == a)
            return a;
        return father[a] = find(father[a]);
    }
    public List<Integer> numIslands2(int n, int m, Point[] operators) {
        List<Integer> list = new ArrayList<>();
        if(n == 0 || m == 0 || operators == null)
            return list;
        int[] cx = {1, 0, -1, 0};
        int[] cy = {0, 1, 0, -1};
        father = new int[n * m];
        isLand = new int[n * m];
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                father[i * m + j] = i * m + j;
                isLand[i * m + j] = 0;
            }
        }
        for(Point point : operators){
            int pos = point.x * m + point.y;
            if(isLand[pos] == 1){
                list.add(count);
                continue;
            }
            isLand[pos] = 1;
            count++;
            for(int i = 0; i < 4; i++){
                int newx = point.x + cx[i];
                int newy = point.y + cy[i];
                int newpos = newx * m + newy;
                if(newx >= 0 && newy >= 0 && newx < n && newy < m && isLand[newpos] == 1){
                    if(find(newpos) != find(pos)){
                        father[find(newpos)] = pos;
                        count--;
                    }
                }
            }
            list.add(count);
        }
        return list;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值