-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathnumberOfConnectedComponents.js
58 lines (47 loc) · 1.46 KB
/
numberOfConnectedComponents.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
51
52
53
54
55
56
57
58
class NumberOfConnectedComponents {
constructor(){
this.parent = [];
this.rank = [];
}
countConnectedComponents(n, edges) {
this.parent = Array(n).fill().map((x, index) => index);
this.rank = Array(n).fill(1);
let count = n;
for(let edge of edges) {
if(this.union(edge[0], edge[1]) === 1) {
count--;
}
}
return count;
}
find(n) {
let curNode = n;
while(curNode !== this.parent[curNode]) {
this.parent[curNode] = this.parent[this.parent[curNode]];
curNode = this.parent[curNode];
}
return curNode;
}
union(n1, n2){
let p1 = this.find(n1), p2 = this.find(n2);
if(p1 === p2) {
return 0;
}
if(this.rank[p1] > this.rank[p2]) {
this.parent[p2] = p1;
this.rank[p1] += this.rank[p2];
} else {
this.parent[p1] = p2;
this.rank[p2] += this.rank[p1];
}
return 1;
}
}
let n1 = 3;
let edges1 = [[0,1], [1,2]];
let n2 = 6;
let edges2 = [[0, 1], [1, 2], [2, 3], [4, 5]];
const numOfConnectedComponents1 = new NumberOfConnectedComponents();
const numOfConnectedComponents2 = new NumberOfConnectedComponents();
console.log(numOfConnectedComponents1.countConnectedComponents(n1, edges1));
console.log(numOfConnectedComponents2.countConnectedComponents(n2, edges2));