Skip to content

Commit c0aeeed

Browse files
authored
Create 1129-shortest-path-with-alternating-colors.kt
1 parent 22485db commit c0aeeed

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Diff for: kotlin/1129-shortest-path-with-alternating-colors.kt

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
fun shortestAlternatingPaths(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray {
3+
val redAdj = Array(n) { ArrayList<Int>() }
4+
val blueAdj = Array(n) { ArrayList<Int>() }
5+
val redVisit = HashSet<Int>()
6+
val blueVisit = HashSet<Int>()
7+
8+
for ((from, to) in redEdges) redAdj[from].add(to)
9+
for ((from, to) in blueEdges) blueAdj[from].add(to)
10+
11+
val res = IntArray(n) { -1 }
12+
13+
with (LinkedList<Pair<Int, Int>>()) {
14+
addFirst(0 to 0)
15+
16+
var len = 0
17+
while (isNotEmpty()) {
18+
repeat (size) {
19+
val (node, c) = removeLast()
20+
if (res[node] == -1) res[node] = len
21+
22+
if (c != -1) {
23+
redAdj[node].forEach {
24+
if (it !in redVisit) {
25+
addFirst(it to -1)
26+
redVisit.add(it)
27+
}
28+
}
29+
}
30+
31+
if (c != 1) {
32+
blueAdj[node].forEach {
33+
if (it !in blueVisit) {
34+
addFirst(it to 1)
35+
blueVisit.add(it)
36+
}
37+
}
38+
}
39+
}
40+
41+
len++
42+
}
43+
}
44+
45+
return res
46+
}
47+
}

0 commit comments

Comments
 (0)