-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickUnion.js
More file actions
63 lines (48 loc) · 1.22 KB
/
quickUnion.js
File metadata and controls
63 lines (48 loc) · 1.22 KB
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
/**
* Union Find Lazy Solution
*/
class UF {
idArr = [];
constructor(n = 10) {
this.idArr = this.makeLocations(n);
}
makeLocations(locationCount) {
const locArr = [];
for (let i = 0; i < locationCount; i++) {
locArr.push(i);
}
return locArr;
}
findRoot(loc) {
if (loc === this.idArr[loc]) return loc;
return this.findRoot(this.idArr[loc]);
}
union(p, q) {
const rootP = this.findRoot(p);
const rootQ = this.findRoot(q);
this.idArr[rootP] = rootQ;
}
connected(p, q) {
return this.findRoot(p) === this.findRoot(q);
}
returnLocArr() {
return this.idArr;
}
}
const unionFind = new UF(10);
unionFind.union(4, 3);
unionFind.union(3, 8);
unionFind.union(6, 5);
unionFind.union(9, 4);
unionFind.union(2, 1);
console.log(unionFind.connected(0, 7)); // true
console.log(unionFind.connected(8, 9)); // false
unionFind.union(5, 0);
console.log(unionFind.connected(0, 7)); // true
console.log(unionFind.connected(8, 9)); // false
unionFind.union(7, 2);
console.log(unionFind.connected(0, 7)); // true
console.log(unionFind.connected(8, 9)); // false
unionFind.union(6, 1);
console.log(unionFind.connected(0, 7)); // true
console.log(unionFind.connected(8, 9)); // true