Skip to content

Commit df607f9

Browse files
authored
number of connected components in an undirected graph solution
1 parent 4a7fd4a commit df607f9

File tree

1 file changed

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

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
/**
3+
* @param n: the number of vertices
4+
* @param edges: the edges of undirected graph
5+
* @return: the number of connected components
6+
*/
7+
fun countComponents(n: Int, edges: Array<IntArray>): Int {
8+
// write your code here
9+
val adj = List(n) {mutableListOf<Int>()}
10+
edges.forEach {
11+
adj[it[0]].add(it[1])
12+
adj[it[1]].add(it[0])
13+
}
14+
val visited = MutableList(n) {false} // T(V, E) = S(V, E) = O(V + E)
15+
val stack = mutableListOf<Int>()
16+
var ans = 0
17+
for (i in 0 until n) {
18+
if (visited[i]) {
19+
continue
20+
}
21+
ans++
22+
visited[i] = true
23+
stack.add(i)
24+
while (! stack.isEmpty()) {
25+
val u = stack.removeLast()
26+
adj[u].filter {! visited[it]}
27+
.forEach {
28+
visited[it] = true
29+
stack.add(it)
30+
}
31+
}
32+
}
33+
return ans
34+
}
35+
}

0 commit comments

Comments
 (0)