Skip to content

Commit 527b81b

Browse files
committed
add 787
1 parent d2251e2 commit 527b81b

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

cheapest-flights-within-k-stops.go

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math"
6+
)
7+
8+
// 787 https://leetcode-cn.com/problems/cheapest-flights-within-k-stops/
9+
// 动态规划
10+
func findCheapestPrice(n int, flights [][]int, src int, dst int, K int) int {
11+
if n < 1 {
12+
return -1
13+
}
14+
matrix := make([][]int, n)
15+
save := make([][]int, n)
16+
for i := 0; i < n; i++ {
17+
matrix[i] = make([]int, n)
18+
save[i] = make([]int, K+1)
19+
}
20+
21+
for i := 0; i < len(flights); i++ {
22+
s, e, v := flights[i][0], flights[i][1], flights[i][2]
23+
matrix[s][e] = v
24+
}
25+
26+
res := math.MaxInt32
27+
queue := make([]int, 0, 2*n)
28+
queue = append(queue, src)
29+
step := 0
30+
31+
for len(queue) > 0 && step <= K {
32+
33+
preLen := len(queue)
34+
if preLen > n {
35+
fmt.Println(len(queue))
36+
}
37+
// fmt.Println("start ", s, " ", queue)
38+
for j := 0; j < preLen; j++ {
39+
s := queue[0]
40+
queue = queue[1:]
41+
for i := 0; i < n; i++ {
42+
if matrix[s][i] <= 0 {
43+
continue
44+
}
45+
if step == 0 {
46+
save[i][step] = 0 + matrix[s][i]
47+
} else {
48+
s := save[s][step-1] + matrix[s][i]
49+
if s < save[i][step] || save[i][step] == 0 {
50+
save[i][step] = s
51+
} else {
52+
continue
53+
}
54+
}
55+
if save[i][step] > res {
56+
continue
57+
}
58+
59+
if i == dst {
60+
res = save[i][step]
61+
}
62+
queue = append(queue, i)
63+
}
64+
}
65+
step++
66+
}
67+
68+
if res == math.MaxInt32 {
69+
return -1
70+
}
71+
return res
72+
}

0 commit comments

Comments
 (0)