kt: add «2685. Count the Number of Complete Components»

URL:	https://leetcode.com/problems/count-the-number-of-complete-components/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-22 23:22:58 +01:00
parent e0c94b7af4
commit ea2ef69f1f
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,49 @@
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
}
}
}