787. K 站中转内最便宜的航班
使用状态转移dp
1 | class Solution { |
Bellman-ford算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[] dist = new int[n+1];
// 初始化距离
Arrays.fill(dist, 1000000000);
dist[src] = 0;
// 只能经过K个中转
for(int i = 0; i <= K; i++){
// copy数组,避免发生数据串联
int[] ds = Arrays.copyOf(dist, dist.length);
// 每次都遍历所有航班
for(int[] flight: flights){
int a = flight[0];
int b = flight[1];
int c = flight[2];
if(dist[b] > ds[a] + c){
dist[b] = Math.min(dist[b], ds[a] + c);
}
}
}
return dist[dst] > 1000000000/2 ? -1 : dist[dst];
}
}
<<<<<<< HEAD
1 | class Solution { |
dijkstra堆优化版算法
1 | class Solution { |
1e1a063b2ed2902f22f9c10fe1fce8bce47a145d