原题链接在这里:https://leetcode.com/problems/cheapest-flights-within-k-stops/

题目:

There are n cities connected by m flights. Each fight starts from city and arrives at v with a price w.

Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from srcto dst with up to k stops. If there is no such route, output -1.

Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph looks like this:

The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph looks like this:

The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.

Note:

  • The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1.
  • The size of flights will be in range [0, n * (n - 1) / 2].
  • The format of each flight will be (src, dst, price).
  • The price of each flight will be in the range [1, 10000].
  • k is in the range of [0, n - 1].
  • There will not be any duplicated flights or self cycles.

题解:

When it comes to Dijkstra, it needs PriorityQueue based on cost.

From the example, if the stops is within K, then it could continue update the total cost.

Create a map first.

Initialize PriorityQueue based on current cost. Put src in it.

When polling out head node, check if it is dst, if it is, it must be smallest cost because of PriorityQueue.

Otherwise, get its stop, it is still smaller than K, and check the graph, get next nestinations and accumlate the cost, add to PriorityQueue.

If until the PriorityQueue is empty, there is no return yet, then there is no such route, return -1.

Time Complexity: O(ElogE). E = flights.length. que size could be E, each add and poll takes logE.

Space: O(E). graph size is O(E). que size is O(E).

AC Java:

 class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
if(n == 0 || K < 0 || flights == null || flights.length == 0 || flights[0].length != 3){
return -1;
} int res = Integer.MAX_VALUE; Map<Integer, List<int []>> graph = new HashMap<>();
for(int [] f : flights){
if(!graph.containsKey(f[0])){
graph.put(f[0], new ArrayList<int []>());
} graph.get(f[0]).add(new int[]{f[1], f[2]});
} PriorityQueue<Node> que = new PriorityQueue<Node>((a, b) -> a.cost-b.cost);
que.add(new Node(src, 0, -1));
while(!que.isEmpty()){
Node cur = que.poll(); if(cur.city == dst){
return cur.cost;
} if(cur.stop < K){
List<int []> nexts = graph.getOrDefault(cur.city, new ArrayList<int []>());
for(int [] next : nexts){
que.add(new Node(next[0], cur.cost+next[1], cur.stop+1));
}
}
} return -1;
}
} class Node{
int city;
int cost;
int stop;
public Node(int city, int cost, int stop){
this.city = city;
this.cost = cost;
this.stop = stop;
}
}

LeetCode 787. Cheapest Flights Within K Stops的更多相关文章

  1. [LeetCode] 787. Cheapest Flights Within K Stops K次转机内的最便宜航班

    There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...

  2. 【LeetCode】787. Cheapest Flights Within K Stops 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:BFS 参考资料 日期 题目 ...

  3. [LeetCode] 787. Cheapest Flights Within K Stops_Medium tag: Dynamic Programming, BFS, Heap

    There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...

  4. 787. Cheapest Flights Within K Stops

    There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...

  5. [LeetCode] Cheapest Flights Within K Stops K次转机内的最便宜的航班

    There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...

  6. [Swift]LeetCode787. K 站中转内最便宜的航班 | Cheapest Flights Within K Stops

    There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...

  7. Within K stops 最短路径 Cheapest Flights Within K Stops

    2018-09-19 22:34:28 问题描述: 问题求解: 本题是典型的最短路径的扩展题,可以使用Bellman Ford算法进行求解,需要注意的是在Bellman Ford算法的时候需要额外申请 ...

  8. Java实现 LeetCode 787 K 站中转内最便宜的航班(两种DP)

    787. K 站中转内最便宜的航班 有 n 个城市通过 m 个航班连接.每个航班都从城市 u 开始,以价格 w 抵达 v. 现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是 ...

  9. LeetCode——787. K 站中转内最便宜的航班

    有 n 个城市通过 m 个航班连接.每个航班都从城市 u 开始,以价格 w 抵达 v. 现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到从 src 到 dst 最多经过 ...

随机推荐

  1. flink checkpoint状态储存三种方式选择

    Flink 提供了三种可用的状态后端:MemoryStateBackend,FsStateBackend,和RocksDBStateBackend. MemoryStateBackend Memory ...

  2. 高并发场景下System.currentTimeMillis()的性能问题的优化

    高并发场景下System.currentTimeMillis()的性能问题的优化 package cn.ucaner.alpaca.common.util.key; import java.sql.T ...

  3. springcolud 的学习(二).微服务架构的介绍

    什么是微服务微服务架是从SOA架构演变过来,比SOA架构粒度会更加精细,让专业的人去做专业的事情(专注),目的提高效率,每个服务于服务之间互不影响,微服务架构中,每个服务必须独立部署,互不影响,微服务 ...

  4. python入学代码

    liwenhu=100 if liwenhu>=90: print("你很棒") elif liwenhu>=80: print("你很不错") e ...

  5. Python进阶(五)----内置函数Ⅱ 和 闭包

    Python进阶(五)----内置函数Ⅱ 和 闭包 一丶内置函数Ⅱ ####内置函数#### 特别重要,反复练习 ###print() 打印输入 #sep 设定分隔符 # end 默认是换行可以打印到 ...

  6. Flutter Platform Channels

    Flutter Platform Channels(一) https://www.jianshu.com/p/33ac774f99b1 https://www.jianshu.com/p/c1e206 ...

  7. 【开发工具】- Atom下载及安装

    原文地址:https://www.jianshu.com/p/c112f024e0ab

  8. 英语DYAMAUND钻石DYAMAUND单词

    dyamaund and the English words dyamaund The Vertu of the Dyamaund": Gemstones, Knowledge and Va ...

  9. 技术圈术语之LDAP

    导语:阅读一些程序的文档时经常看到支持ldap,由于对这个协议不太熟悉,平时也没有用过,所以一直也没怎么留意,今天看rabbitmq的文档又发现了ldap相关的介绍,于是想把这个问题搞清楚. 一.LD ...

  10. trackingjs+websocket+百度人脸识别API,实现人脸签到

    在公司做了个年会的签到.抽奖系统.用java web做的,用公司的办公app扫二维码码即可签到,扫完码就在大屏幕上显示这个人的照片.之后领导让我改得高大上一点,用人脸识别来签到,就把扫二维码的步骤改成 ...