注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
感觉要求变高了
我的代码如下。朋友说,需要用dp来记录??? 我都不懂为啥呢?- class Solution {
-
- public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
-
- Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
-
- for(int[] f : flights){
-
- if(!map.containsKey(f[0])){
-
- map.put(f[0], new HashMap<>());
- }
-
- map.get(f[0]).put(f[1],f[2]);
-
- }
-
- Queue<int[]> queue = new PriorityQueue<>( (a,b) -> (a[0] - b[0]) );
-
- Set<Integer> set = new HashSet<>();
-
- set.add(src);
-
- int best[] = new int[n+1];
-
- Arrays.fill(best, Integer.MAX_VALUE);
-
- best[src] = 0;
-
- queue.add(new int[]{0, src, k+1});
-
- while( !queue.isEmpty() ){
-
- int[] curr = queue.poll();
-
- int currPrice = curr[0];
- int currLocation = curr[1];
- int stopsLeft = curr[2];
-
- if(currLocation == dst) return currPrice;
-
- Map<Integer, Integer> neighhors = map.getOrDefault(currLocation, new HashMap<>());
-
- if(stopsLeft > 0){
-
- for(int nei : neighhors.keySet()){
-
- set.add(nei);
-
- int newPrice = currPrice + neighhors.get(nei);
-
- if( newPrice < best[nei] ) {
- queue.add(new int[]{currPrice + neighhors.get(nei), nei, stopsLeft - 1});
-
- }
- }
- }
- }
-
- return -1;
- }
- }
复制代码 |