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

Commit ceb1160

Browse files
committed
Solve 787. Cheapest Flights Within K Stops
1 parent 700220c commit ceb1160

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
3+
fun findCheapestPrice(n: Int, flights: Array<IntArray>, src: Int, dst: Int, k: Int): Int {
4+
var distances = IntArray(n) { Int.MAX_VALUE }
5+
distances[src] = 0
6+
7+
repeat(k + 1) {
8+
val newDistances = distances.copyOf()
9+
10+
flights.forEach { flight ->
11+
val from = flight[0]
12+
val to = flight[1]
13+
val cost = flight[2]
14+
15+
if (distances[from] != Int.MAX_VALUE) {
16+
newDistances[to] = minOf(newDistances[to], distances[from] + cost)
17+
}
18+
}
19+
20+
distances = newDistances
21+
}
22+
23+
return when {
24+
distances[dst] == Int.MAX_VALUE -> -1
25+
else -> distances[dst]
26+
}
27+
}
28+
29+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /