File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments