并查集的理解与实现
这里通过一个例子来讲解一下并查集
问题 我们要判断一个无向图中是否存在环,如果存在的话就返回Ture,否则的话就返回False。
代码的实现
进行路径路径优化是通过增加一个rank数组来记录根结点对应的数的高度,以此来判断当找到两个要合并的两个根结点的时候,应该将哪一个作为新的根结点,哪一个作为其子树。
public class Main {
public static void main(String[] args) {
//并查集,外加压缩路径进行优化
final int VERTICES=6;
int[] parent=new int[VERTICES];
int[] rank=new int[VERTICES];
int[][] edges={{0,1},{1,2},{1,3},{3,4},{2,4},{2,5}};
Arrays.fill(rank,0);
Arrays.fill(parent,-1);
int i;
for(i=0;i<6;++i){
int x=edges[i][0];
int y=edges[i][1];
if(union_vertices(x,y,parent,rank)==0){
System.out.println("存在环,结束!");
return;
}
}
System.out.println("不存在环!");
}
public static int find_root(int x,int[] parent){
int x_root=x;
while (parent[x_root]!=-1){
x_root=parent[x_root];
}
return x_root;
}
/**
* 返回1代表合并成功,返回0代表存在环失败
* */
public static int union_vertices(int x, int y, int[] parent, int[] rank) {
int x_root=find_root(x,parent);
int y_root=find_root(y,parent);
if(x_root==y_root){
return 0;
}else {
//parent[x_root]=y_root; //这是优化之前的代码
if(rank[x_root]>rank[y_root]){
parent[y_root]=x_root;
}else if(rank[x_root]<rank[y_root]){
parent[x_root]=y_root;
}else {
parent[x_root]=y_root;
rank[y_root]++;
}
return 1;
}
}
}
并查集模板
class UnionFind {
int [ ] parent;
int [ ] size;
int n;
int setCount;
public UnionFind ( int n) {
this . n = n;
this . setCount = n;
this . parent = new int [ n] ;
this . size = new int [ n] ;
Arrays . fill ( size, 1 ) ;
for ( int i = 0 ; i < n; ++ i) {
parent[ i] = i;
}
}
public int findset ( int x) {
return parent[ x] == x ? x : ( parent[ x] = findset ( parent[ x] ) ) ;
}
public boolean unite ( int x, int y) {
x = findset ( x) ;
y = findset ( y) ;
if ( x == y) {
return false ;
}
if ( size[ x] < size[ y] ) {
int temp = x;
x = y;
y = temp;
}
parent[ y] = x;
size[ x] += size[ y] ;
-- setCount;
return true ;
}
public boolean connected ( int x, int y) {
x = findset ( x) ;
y = findset ( y) ;
return x == y;
}
}