-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathunion-find.js
42 lines (34 loc) · 970 Bytes
/
union-find.js
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
class UnionFind {
constructor(count) {
this.count = count;
this.parent = new Array(count);
this.rank = new Array(count);
for (let i = 0; i < count; ++i) {
this.parent[i] = i;
this.rank[i] = 1;
}
}
find(p) {
while (p != this.parent[p]) {
this.parent[p] = this.parent[this.parent[p]];
p = this.parent[p];
}
return p;
}
union(p, q) {
let rootP = this.find(p),
rootQ = this.find(q);
if (rootP == rootQ) return;
let rankP = this.rank[p],
rankQ = this.rank[q];
if (rankP < rankQ) this.parent[rootP] = rootQ;
else if (rankP > rankQ) this.parent[rootQ] = rootP;
else {
this.parent[rootP] = rootQ;
this.rank[rootP] += 1;
}
}
isConnected(p, q) {
return this.find(p) == this.find(q);
}
}