-
Notifications
You must be signed in to change notification settings - Fork 3
/
UnionFind.java
71 lines (54 loc) · 1.45 KB
/
UnionFind.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
59
60
61
62
63
64
65
66
67
68
69
70
71
package Graphs;
import java.util.Arrays;
public class UnionFind {
private final int size;
private int[] id;
private int[] treeSize;
private int numComponents;
public UnionFind(int size) {
this.size = size;
id = new int[size];
for (int i = 0; i < size; i++) {
id[i] = i;
}
Arrays.fill(treeSize, 1);
numComponents = size;
}
public void union(int p, int q) {
check(p);
check(q);
int rootQ = find(q);
int rootP = find(p);
if (rootQ == rootP) return;
if (treeSize[rootQ] > treeSize[rootP]) {
id[rootP] = rootQ;
treeSize[rootQ] += treeSize[rootP];
} else {
id[rootQ] = rootP;
treeSize[rootP] += treeSize[rootQ];
}
numComponents--;
}
public int find(int index) {
check(index);
int root = index;
while (root != id[root]) {
root = id[root];
}
while (index != root) {
int temp = id[index];
id[index] = root;
index = temp;
}
return root;
}
public boolean connected(int p, int q) {
return (find(p) == find(q));
}
public int numberComponents() {
return numComponents;
}
private void check(int index) {
if (index < 0 || index > size) throw new IllegalArgumentException("Index must be between zero and size.");
}
}