Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7be9da6

Browse files
authored
Merge pull request neetcode-gh#789 from MaratKhakim/787-Cheapest-Flights-Go
GO: 787. Cheapest Flights within K Stops
2 parents c577488 + bd0a61d commit 7be9da6

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int {
2+
cost := make([]int, n)
3+
4+
for i := 0; i < n; i++ {
5+
cost[i] = math.MaxUint32
6+
}
7+
8+
cost[src] = 0
9+
10+
for i := 0; i <= k; i++ {
11+
temp := make([]int, n)
12+
copy(temp, cost)
13+
14+
for j := 0; j < len(flights); j++ {
15+
from, to, price := flights[j][0], flights[j][1], flights[j][2]
16+
17+
if cost[from] != math.MaxUint32 {
18+
temp[to] = min(temp[to], cost[from]+price)
19+
}
20+
}
21+
22+
cost = temp
23+
}
24+
25+
if cost[dst] == math.MaxUint32 {
26+
return -1
27+
}
28+
29+
return cost[dst]
30+
}
31+
32+
func min(x, y int) int {
33+
if x > y {
34+
return y
35+
}
36+
37+
return x
38+
}

0 commit comments

Comments
 (0)