Skip to content

Commit aec0ed1

Browse files
committed
수정
1 parent 2122f12 commit aec0ed1

File tree

1 file changed

+39
-39
lines changed
  • number-of-connected-components-in-an-undirected-graph

1 file changed

+39
-39
lines changed
Lines changed: 39 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,44 @@
11
export class Solution {
2-
/**
3-
* @param {number} n - the number of vertices
4-
* @param {number[][]} edges - the edges of undirected graph
5-
* @return {number} - the number of connected components
6-
*/
7-
countComponents(n, edges) {
8-
const par = Array.from({ length: n }, (_, i) => i);
9-
const rank = Array(n).fill(1);
10-
11-
const find = (n1) => {
12-
let res = n1;
13-
while (res !== par[res]) {
14-
par[res] = par[par[res]]; // path compression
15-
res = par[res];
16-
}
17-
return res;
18-
};
19-
20-
const union = (n1, n2) => {
21-
const p1 = find(n1);
22-
const p2 = find(n2);
23-
if (p1 === p2) return 0;
24-
25-
if (rank[p2] > rank[p1]) {
26-
par[p1] = p2;
27-
rank[p2] += rank[p1];
28-
} else {
29-
par[p2] = p1;
30-
rank[p1] += rank[p2];
31-
}
32-
33-
return 1;
34-
};
35-
36-
let res = n;
37-
for (const [n1, n2] of edges) {
38-
res -= union(n1, n2);
2+
/**
3+
* @param {number} n - the number of vertices
4+
* @param {number[][]} edges - the edges of undirected graph
5+
* @return {number} - the number of connected components
6+
*/
7+
countComponents(n, edges) {
8+
const par = Array.from({ length: n }, (_, i) => i);
9+
const rank = Array(n).fill(1);
10+
11+
const find = (n1) => {
12+
let res = n1;
13+
while (res !== par[res]) {
14+
par[res] = par[par[res]]; // path compression
15+
res = par[res];
3916
}
40-
4117
return res;
18+
};
19+
20+
const union = (n1, n2) => {
21+
const p1 = find(n1);
22+
const p2 = find(n2);
23+
if (p1 === p2) return 0;
24+
25+
if (rank[p2] > rank[p1]) {
26+
par[p1] = p2;
27+
rank[p2] += rank[p1];
28+
} else {
29+
par[p2] = p1;
30+
rank[p1] += rank[p2];
31+
}
32+
33+
return 1;
34+
};
35+
36+
let res = n;
37+
for (const [n1, n2] of edges) {
38+
res -= union(n1, n2);
4239
}
40+
41+
return res;
4342
}
44-
43+
}
44+

0 commit comments

Comments
 (0)