forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber of Provinces.js
50 lines (49 loc) · 1.3 KB
/
Number of Provinces.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
43
44
45
46
47
48
49
50
// Runtime: 110 ms (Top 51.77%) | Memory: 45.5 MB (Top 30.12%)
function DisjointSet (size) {
this.root = []
this.rank = []
this.size = size
for (let i = 0; i < size; i++) {
this.root.push(i)
this.rank.push(1)
}
this.find = function(x) {
if (x === this.root[x]) {
return x
}
this.root[x] = this.find(this.root[x])
return this.root[x]
}
this.union = function(x, y) {
const rootX = this.find(x)
const rootY = this.find(y)
if (rootX === rootY) return
this.size--
if (this.rank[rootX] > this.rank[rootY]) {
this.root[rootY] = this.root[rootX]
}
else if (this.rank[rootX] < this.rank[rootY]) {
this.root[rootX] = this.root[rootY]
}
else {
this.root[rootY] = this.root[rootX]
this.rank[rootX]++
}
}
}
/**
* @param {number[][]} isConnected
* @return {number}
*/
var findCircleNum = function(isConnected) {
const n = isConnected.length
const disjointSet = new DisjointSet(isConnected.length)
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (isConnected[i][j]) {
disjointSet.union(i, j)
}
}
}
return disjointSet.size
};