leetcode787.K站中转最便宜航班

思路:将出发点加入小顶堆 中,之后每优先处理价格最小的那一段路径,若是终点则返回价格,否则再走一步,并且加入到堆中放到下一批处理;

也就是每一次优先处理价格最小的

 1 class Solution {
 2     public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
 3         int [][] g = new int[n][n];
 4         for(int []f : flights){
 5             g[f[0]][f[1]] = f[2];
 6         }
 7         PriorityQueue<int []> heap = new PriorityQueue<>(new Comparator<int[]>(){
 8             public int compare(int [] o1, int [] o2){
 9                 return o1[0] - o2[0];
10             }
11         });
12         heap.offer(new int[]{0,src,K+1});
13         while(!heap.isEmpty()){
14             int [] t = heap.poll();
15             int price = t[0];//这样不容易弄混数组中值的含义
16             int place = t[1];
17             int remainSteps = t[2];
18             if(place == dst){
19                 return price;
20             }
21             if(remainSteps > 0){
22                 for(int i = 0; i < n; i++){
23                     if(g[place][i] > 0){
24                         heap.offer(new int[]{price + g[place][i], i, remainSteps - 1});
25                     }
26                 }
27             }
28         }
29         return -1;
30     }
31 }

2020/09/09

原文地址:https://www.cnblogs.com/yu-xia-zheng-ye/p/13637736.html