kt: add «3243. Shortest Distance After Road Addition Queries I»

URL:	https://leetcode.com/problems/shortest-distance-after-road-addition-queries-i/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-11-27 22:13:03 +01:00
parent 97f7ee5480
commit f487729a83
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,35 @@
class Solution {
private fun findMinDistance(
n: Int,
graph: List<MutableList<Int>>,
): Int {
val dp = IntArray(n)
for (u in (0..n - 2).reversed()) {
dp[u] = graph[u].minOfOrNull { v -> 1 + dp[v] } ?: n
}
return dp[0]
}
fun shortestDistanceAfterQueries(
n: Int,
queries: Array<IntArray>,
): IntArray {
val distances = IntArray(queries.size)
// Construct initial graph
val graph = (1..n).map { mutableListOf(it) }.toList()
graph.last().removeLast()
// Process queries
for (query in queries.withIndex()) {
val (u, v) = query.value[0] to query.value[1]
graph[u].add(v)
distances[query.index] = findMinDistance(n, graph)
}
return distances
}
}