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