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:
parent
e0c94b7af4
commit
ea2ef69f1f
1 changed files with 49 additions and 0 deletions
49
kt/count-the-number-of-complete-components.kt
Normal file
49
kt/count-the-number-of-complete-components.kt
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue