-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortestPathWithAlternatingColors.kt
38 lines (35 loc) · 1.39 KB
/
shortestPathWithAlternatingColors.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fun shortestAlternatingPaths(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray {
val graph = redEdges.asSequence()
.map { (a, b) -> a to (b to true) }
.groupingBy { it.first }
.fold({ _, _ -> mutableListOf<Pair<Int, Boolean>>()}) { _, acc, element ->
acc.also { acc += element.second }
}
.toMutableMap()
blueEdges.asSequence().forEach { (a, b) -> graph.getOrPut(a) { mutableListOf() } += b to false }
val result = MutableList<Int?>(n) { null }
val visited = MutableList(n * 2) { false }
var q = listOf(0 to false, 0 to true)
result[0] = 0
visited[0] = true
visited[n] = true
var i = 0
while (q.isNotEmpty()) {
i++
q = q.asSequence()
.flatMap { (j, flag) ->
graph[j]
?.let { edges ->
edges.asSequence()
.filter { !visited[it.first + if (it.second) n else 0] && it.second != flag }
.onEach {
result[it.first] = minOf(result[it.first] ?: Int.MAX_VALUE, i)
visited[it.first + if (it.second) n else 0] = true
}
}
.orEmpty()
}
.toList()
}
return result.asSequence().map { it ?: -1 }.toList().toIntArray()
}