Skip to content

Commit e94e807

Browse files
committed
feat: Add solution for LeetCode problem 323
1 parent 7dcd690 commit e94e807

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//
2+
// 323. Number of Connected Components in an Undirected Graph
3+
// https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/07/06.
7+
//
8+
9+
final class Solution {
10+
func countComponents(_ n: Int, _ edges: [[Int]]) -> Int {
11+
var visited: Set<Int> = []
12+
var count = 0
13+
14+
var graph: [Int: [Int]] = [:]
15+
16+
for edge in edges {
17+
graph[edge[0], default: []].append(edge[1])
18+
graph[edge[1], default: []].append(edge[0])
19+
}
20+
21+
func dfs(_ node: Int) {
22+
if visited.contains(node) {
23+
return
24+
}
25+
26+
visited.insert(node)
27+
28+
for nextNode in graph[node, default: []] {
29+
dfs(nextNode)
30+
}
31+
}
32+
33+
for node in 0 ..< n where !visited.contains(node) {
34+
count += 1
35+
dfs(node)
36+
}
37+
38+
return count
39+
}
40+
}

0 commit comments

Comments
 (0)