Skip to content

Commit 450f2ca

Browse files
committed
solve
1 parent ae26fb8 commit 450f2ca

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
// O(n+m) (m = edges.count) time / O(n+m) space
3+
func countComponents(_ n: Int, _ edges: [[Int]]) -> Int {
4+
var graph = [[Int]](repeating: [], count: n)
5+
for edge in edges {
6+
graph[edge[0]].append(edge[1])
7+
graph[edge[1]].append(edge[0])
8+
}
9+
10+
var visited = [Bool](repeating: false, count: n)
11+
var connectedComponents = 0
12+
13+
for i in 0..<n {
14+
if visited[i] {
15+
continue
16+
}
17+
var queue = [Int]()
18+
queue.append(i)
19+
visited[i] = true
20+
var head = 0
21+
22+
while queue.count > head {
23+
let current = queue[head]
24+
head += 1
25+
26+
for node in graph[current] {
27+
if !visited[node] {
28+
visited[node] = true
29+
queue.append(node)
30+
}
31+
}
32+
}
33+
connectedComponents += 1
34+
}
35+
36+
return connectedComponents
37+
}
38+
}
39+
40+
print(Solution().countComponents(3, [[0,1], [0,2]]))
41+
print(Solution().countComponents(6, [[0,1], [1,2], [2, 3], [4, 5]] ))

0 commit comments

Comments
 (0)