Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc0aeeed

Browse files
authored
Create 1129-shortest-path-with-alternating-colors.kt
1 parent22485db commitc0aeeed

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
classSolution {
2+
funshortestAlternatingPaths(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 to0)
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 to1)
35+
blueVisit.add(it)
36+
}
37+
}
38+
}
39+
}
40+
41+
len++
42+
}
43+
}
44+
45+
return res
46+
}
47+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp