-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnionFindSet.java
58 lines (47 loc) · 1.05 KB
/
UnionFindSet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package maze;
import java.util.Collections;
/**
* 基本并查集
*/
public class UnionFindSet{
public static final int DEFAULT_SIZE = 100;
private int[] father;
public UnionFindSet() {
father = new int[DEFAULT_SIZE];
init();
}
public UnionFindSet(int size){
father = new int[size];
init();
}
public boolean isConnected(int x,int y){
return find(x) == find(y);
}
public int find(int x){
int r = x;
//找到根节点
while ( r != father[r])
r = father[r];
//路径压缩
int i = x,j;
while (i != r){
j = father[i];
father[i] = r;
i = j;
}
return r;
}
public void union(int x ,int y){
int fx = find(x);
int fy = find(y);
if(fx == fy) return;
else if(fx > fy)
father[fx] = fy;
else
father[fy] = fx;
}
private void init(){
for (int i = 0;i<father.length;i++)
father[i] = i;
}
}