File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ // Time Complexity: O(n + e)
3
+ // Space Complexity: O(n + e)
4
+ // n : number of nodes
5
+ // e : number of edges
6
+ fun countComponents (n : Int , edges : Array <IntArray >): Int {
7
+ val graph = Array (n) { mutableListOf<Int >() }
8
+ for (edge in edges) { // make graph
9
+ graph[edge[0 ]].add(edge[1 ])
10
+ graph[edge[1 ]].add(edge[0 ])
11
+ }
12
+ val visited = BooleanArray (n) // visited array
13
+ var count = 0 // number of connected components
14
+
15
+ for (i in 0 until n) {
16
+ if (! visited[i]) {
17
+ dfs(i, graph, visited)
18
+ count++
19
+ }
20
+ }
21
+ return count
22
+ }
23
+
24
+ fun dfs (node : Int , graph : Array <MutableList <Int >>, visited : BooleanArray ) {
25
+ visited[node] = true
26
+ for (neighbor in graph[node]) {
27
+ if (! visited[neighbor]) {
28
+ dfs(neighbor, graph, visited)
29
+ }
30
+ }
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments