-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnionFind.java
More file actions
44 lines (35 loc) · 768 Bytes
/
UnionFind.java
File metadata and controls
44 lines (35 loc) · 768 Bytes
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
class UnionFind {
private int[] tree;
public UnionFind(int size) {
tree = new int[size];
for (int i = 0; i < size; i++) {
tree[i] = -1;
}
}
public int root(int node) {
if (tree[node] < 0) {
return node;
}
else {
return tree[node] = root(tree[node]);
}
}
public boolean same(int x, int y) {
return root(x) == root(y);
}
public void unite(int x, int y) {
x = root(x);
y = root(y);
if (x == y) {
return;
}
else {
tree[x] += tree[y];
tree[y] = x;
return;
}
}
public int size(int node) {
return -1 * root(node);
}
}