URL: https://leetcode.com/problems/count-the-number-of-complete-components/ Signed-off-by: Matej Focko <me@mfocko.xyz>
49 lines
1.3 KiB
Kotlin
49 lines
1.3 KiB
Kotlin
class Solution {
|
|
private fun makeGraph(
|
|
n: Int,
|
|
edges: Array<IntArray>,
|
|
): Array<MutableList<Int>> =
|
|
Array<MutableList<Int>>(n) { mutableListOf<Int>() }.let { g ->
|
|
edges.forEach { e ->
|
|
val (u, v) = e[0] to e[1]
|
|
g[u].add(v)
|
|
g[v].add(u)
|
|
}
|
|
|
|
g
|
|
}
|
|
|
|
private fun dfs(
|
|
graph: Array<MutableList<Int>>,
|
|
visited: BooleanArray,
|
|
u: Int,
|
|
): Pair<Int, Int> =
|
|
when (visited[u]) {
|
|
true -> 0 to 0
|
|
else -> {
|
|
visited[u] = true
|
|
var (vertices, edges) = 1 to graph[u].size
|
|
|
|
graph[u].forEach { v ->
|
|
dfs(graph, visited, v).let { (newVertices, newEdges) ->
|
|
vertices += newVertices
|
|
edges += newEdges
|
|
}
|
|
}
|
|
|
|
vertices to edges
|
|
}
|
|
}
|
|
|
|
fun countCompleteComponents(
|
|
n: Int,
|
|
edges: Array<IntArray>,
|
|
): Int =
|
|
(makeGraph(n, edges) to BooleanArray(n)).let { (g, visited) ->
|
|
visited.indices.asSequence().filter { u -> !visited[u] }.count { u0 ->
|
|
val (vertices, edges) = dfs(g, visited, u0)
|
|
|
|
vertices * (vertices - 1) == edges
|
|
}
|
|
}
|
|
}
|