forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1129-shortest-path-with-alternating-colors.kt
47 lines (39 loc) · 1.43 KB
/
1129-shortest-path-with-alternating-colors.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
39
40
41
42
43
44
45
46
47
class Solution {
fun shortestAlternatingPaths(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray {
val redAdj = Array(n) { ArrayList<Int>() }
val blueAdj = Array(n) { ArrayList<Int>() }
val redVisit = HashSet<Int>()
val blueVisit = HashSet<Int>()
for ((from, to) in redEdges) redAdj[from].add(to)
for ((from, to) in blueEdges) blueAdj[from].add(to)
val res = IntArray(n) { -1 }
with (LinkedList<Pair<Int, Int>>()) {
addFirst(0 to 0)
var len = 0
while (isNotEmpty()) {
repeat (size) {
val (node, c) = removeLast()
if (res[node] == -1) res[node] = len
if (c != -1) {
redAdj[node].forEach {
if (it !in redVisit) {
addFirst(it to -1)
redVisit.add(it)
}
}
}
if (c != 1) {
blueAdj[node].forEach {
if (it !in blueVisit) {
addFirst(it to 1)
blueVisit.add(it)
}
}
}
}
len++
}
}
return res
}
}