Skip to content

Commit 388218b

Browse files
committed
Number of Connected Components in an Undirected Graph
1 parent d0dbce0 commit 388218b

File tree

1 file changed

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

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
}

0 commit comments

Comments
 (0)