【查并集】java代码实现
作者:互联网
思路
查并集是针对多树情况下的一种处理方式,核心是两个方法
1.find():用于在多树情况下检查两个节点是否属于同一棵树内
2.join():用于合并两棵树
节点类构造
info用于存储信息,pre用于存储该节点的前驱节点,isFather用于表示该节点是否是父亲节点
private int info;
private Point pre=null;
private Boolean isFather=true;
find()方法
递归获取该节点的最终父节点
public Point findFather(Point p){
if(p.getPre()==null){
return p;
}else{
return findFather(p.getPre());
}
}
join()方法
传入两节点并取这两个节点的父节点,进行比较,若两节点归属于同意父节点则结束运行,若两节点归属于不同父节点则取其中一个节点的父节点以子节点的身份加入另一棵树
public void join(Point p1,Point p2){
Point p1Father = findFather(p1);
Point p2Father = findFather(p2);
if(p1.equals(p2)){
return;
}else{
p1Father.setFather(false);
p1Father.setPre(p2Father);
}
}
完整代码
节点类
package FindJoinSet;
public class Point {
private int info;
private Point pre=null;
private Boolean isFather=true;
public Boolean getFather() {
return isFather;
}
public void setFather(Boolean father) {
isFather = father;
}
public int getInfo() {
return info;
}
public void setInfo(int info) {
this.info = info;
}
public Point getPre() {
return pre;
}
public void setPre(Point pre) {
this.pre = pre;
}
}
并查集类
package FindJoinSet;
public class FindJoinSet {
public Point findFather(Point p){
if(p.getPre()==null){
return p;
}else{
return findFather(p.getPre());
}
}
public void join(Point p1,Point p2){
Point p1Father = findFather(p1);
Point p2Father = findFather(p2);
if(p1.equals(p2)){
return;
}else{
p1Father.setFather(false);
p1Father.setPre(p2Father);
}
}
}
标签:pre,java,Point,实现,代码,节点,findFather,return,public 来源: https://blog.csdn.net/weixin_42270132/article/details/121718213