并查集代码实现

该作者已经将并查集原理讲述的非常清楚 传送门:博客地址

并查集实现代码

使用了路径压索和连接优化

package com.algorithm.unionFind;

public class UnionFind {
    private int [] group, groupSize;
    private int groupNum;

    /**
     * 初始化
     * @param num
     */
    UnionFind(int num){
        group = new int[num];
        groupSize = new int[num];
        groupNum = num;
        for(int i = 0;i<num;i++){
            group[i] = i;
            groupSize[i] = 1;
        }
    }

    /**
     *
     * 查询节点node属于的组
     * @param node
     * @return
     */
    public int find(int node){
        while(node != group[node]){
            group[node] = group[group[node]];
            node = group[node];
        }
        return node;
    }

    /**
     * 连接两个节点nodePre,nodePost,使之属于同一个组
     * @param nodePre
     * @param nodePost
     * @return
     */
    public void union(int nodePre, int nodePost){
        int nodePreRoot = find(nodePre);
        int nodePostRoot = find(nodePost);
        if(nodePostRoot == nodePreRoot) return ;
        if(groupSize[nodePostRoot] > groupSize[nodePreRoot]) {
            group[nodePreRoot] = nodePostRoot;
            groupSize[nodePostRoot] += groupSize[nodePreRoot];
        }
        else{
            group[nodePostRoot ] = nodePreRoot;
            groupSize[nodePreRoot] += groupSize[nodePostRoot];
        }
        groupNum -- ;
    }

    /**
     * 判断两个节点之间是否是联通的
     * @param nodePre
     * @param nodePost
     * @return
     */
    public boolean isConnected(int nodePre, int nodePost){
        return find(nodePre) == find(nodePost);
    }

    /**
     * 获取组的数目
     * @return
     */
    public int getCount(){
        return groupNum;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值