Skip to content

Commit 33c9fd6

Browse files
authored
Update 1627-graph-connectivity-with-threshold.js
1 parent d2897c7 commit 33c9fd6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

1627-graph-connectivity-with-threshold.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,53 @@
1+
/**
2+
* @param {number} n
3+
* @param {number} threshold
4+
* @param {number[][]} queries
5+
* @return {boolean[]}
6+
*/
7+
const areConnected = function(n, threshold, queries) {
8+
const arr = []
9+
const uf = new UF(n)
10+
setup(n, threshold, uf)
11+
for(let i = 0, len = queries.length; i < len;i++) {
12+
arr.push(uf.check(queries[i][0], queries[i][1]))
13+
}
14+
return arr
15+
};
16+
17+
function setup(n, t, uf) {
18+
for (let i = t + 1; i <= n; i++) {
19+
let m = 1;
20+
while (i * m <= n) {
21+
uf.union(i, i * m);
22+
m += 1;
23+
}
24+
}
25+
}
26+
27+
28+
class UF {
29+
constructor(n) {
30+
this.root = Array(n).fill(null).map((_, i) => i)
31+
}
32+
find(x) {
33+
if (this.root[x] !== x) {
34+
this.root[x] = this.find(this.root[x])
35+
}
36+
return this.root[x]
37+
}
38+
union(x, y) {
39+
const xr = this.find(x)
40+
const yr = this.find(y)
41+
this.root[yr] = xr
42+
}
43+
check(x, y) {
44+
return this.find(x) === this.find(y)
45+
}
46+
}
47+
48+
49+
// another
50+
151
/**
252
* @param {number} n
353
* @param {number} threshold

0 commit comments

Comments
 (0)