Skip to content

Commit cb5c320

Browse files
committed
feat(soobing): week12 > number-of-connected-components-in-an-undirected-graph
1 parent 8e3b199 commit cb5c320

File tree

1 file changed

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

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
* 문제 설명
3+
* - 무방향 그래프에서 연결된 노드의 갯수를 구하는 문제
4+
*
5+
* 아이디어
6+
* 1) 그래프 생성 + DFS로 탐색
7+
* 2) Union-Find -> ⚠️ 다음에 이걸로 해보기
8+
* - 모든 노드를 자기 자신을 부모로 초기화
9+
* - 각 edge에 대해 union 연산 수행
10+
* - 최종적으로 남아있는 루트(대표 노드)의 개수가 연결 요소 수
11+
*/
12+
function countComponents(n: number, edges: number[][]): number {
13+
const graph: Record<number, number[]> = {};
14+
for (let i = 0; i < n; i++) graph[i] = [];
15+
16+
for (const [a, b] of edges) {
17+
graph[a].push(b);
18+
graph[b].push(a);
19+
}
20+
21+
const visited = new Set<number>();
22+
let count = 0;
23+
24+
const dfs = (node: number) => {
25+
visited.add(node);
26+
for (const neighbor of graph[node]) {
27+
if (!visited.has(neighbor)) {
28+
dfs(neighbor);
29+
}
30+
}
31+
};
32+
33+
for (let i = 0; i < n; i++) {
34+
if (!visited.has(i)) {
35+
dfs(i);
36+
count++;
37+
}
38+
}
39+
40+
return count;
41+
}
42+
43+
function countComponents2(n: number, edges: number[][]): number {
44+
const parent = Array(n)
45+
.fill(0)
46+
.map((_, i) => i);
47+
48+
// find 함수 (경로 압축 포함)
49+
const find = (x: number): number => {
50+
if (parent[x] !== x) {
51+
parent[x] = find(parent[x]);
52+
}
53+
return parent[x];
54+
};
55+
56+
// union 함수 (다른 집합이면 병합하고 true 반환)
57+
const union = (x: number, y: number): boolean => {
58+
const rootX = find(x);
59+
const rootY = find(y);
60+
if (rootX === rootY) return false;
61+
parent[rootX] = rootY;
62+
return true;
63+
};
64+
65+
let count = n;
66+
67+
for (const [a, b] of edges) {
68+
if (union(a, b)) {
69+
count--; // 서로 다른 집합을 연결했으므로 연결 요소 수 줄임
70+
}
71+
}
72+
73+
return count;
74+
}

0 commit comments

Comments
 (0)