Number of Provinces LeetCode solution in JavaScript

1
function DisjointSet(size) {
2
this.root = [];
3
this.rank = [];
4
this.size = size;
5
for (let i = 0; i < size; i++) {
6
this.root.push(i);
7
this.rank.push(1);
8
}
9
this.find = function (x) {
10
if (x === this.root[x]) {
11
return x;
12
}
13
this.root[x] = this.find(this.root[x]);
14
return this.root[x];
15
};
16
this.union = function (x, y) {
17
const rootX = this.find(x);
18
const rootY = this.find(y);
19
if (rootX === rootY) return;
20
this.size--;
21
if (this.rank[rootX] > this.rank[rootY]) {
22
this.root[rootY] = this.root[rootX];
23
} else if (this.rank[rootX] < this.rank[rootY]) {
24
this.root[rootX] = this.root[rootY];
25
} else {
26
this.root[rootY] = this.root[rootX];
27
this.rank[rootX]++;
28
}
29
};
30
}
31

32
/**
33
* @param {number[][]} isConnected
34
* @return {number}
35
*/
36
var findCircleNum = function (isConnected) {
37
const n = isConnected.length;
38
const disjointSet = new DisjointSet(isConnected.length);
39
for (let i = 0; i < n; i++) {
40
for (let j = 0; j < n; j++) {
41
if (isConnected[i][j]) {
42
disjointSet.union(i, j);
43
}
44
}
45
}
46
return disjointSet.size;
47
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0