LeetCode 787. Cheapest Flights Within K Stops
原题链接在这里:https://leetcode.com/problems/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 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 src
to 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 city0
to city2
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 city0
to city2
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 from0
ton
- 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的更多相关文章
- [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 ...
- 【LeetCode】787. Cheapest Flights Within K Stops 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:BFS 参考资料 日期 题目 ...
- [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 ...
- 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 ...
- [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 ...
- [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 ...
- Within K stops 最短路径 Cheapest Flights Within K Stops
2018-09-19 22:34:28 问题描述: 问题求解: 本题是典型的最短路径的扩展题,可以使用Bellman Ford算法进行求解,需要注意的是在Bellman Ford算法的时候需要额外申请 ...
- Java实现 LeetCode 787 K 站中转内最便宜的航班(两种DP)
787. K 站中转内最便宜的航班 有 n 个城市通过 m 个航班连接.每个航班都从城市 u 开始,以价格 w 抵达 v. 现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是 ...
- LeetCode——787. K 站中转内最便宜的航班
有 n 个城市通过 m 个航班连接.每个航班都从城市 u 开始,以价格 w 抵达 v. 现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到从 src 到 dst 最多经过 ...
随机推荐
- Python 入门(1):hello world 到流程控制
1.hello world 在D:\python\目录下新建文件hello.txt,编写代码如下 print("hello world!") 修改后缀名为.py,执行hello.p ...
- HTTP: Request中的post和get区别
* GET和POST之间的主要区别 1.GET是从服务器上获取数据,POST是向服务器传送数据. 2.在客户端, get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段 ...
- STM32 系统滴答计时器
;//us与系统滴答的被乘数 ;//ms与系统滴答的被乘数 ;//系统运行秒数 /** * @description:系统滴答计时系统初始化 * @param 无 * @retval 无 */ voi ...
- 4. Spark Streaming解析
4.1 初始化StreamingContext import org.apache.spark._ import org.apache.spark.streaming._ val conf = new ...
- CLRS10.2-4练习 - 修改链表查询方法
要求: As written, each loop iteration in the LIST-SEARCH' procedure requires two tests:one for x ≠ L.n ...
- golang 之 flag
针对官网对flag 的定义解释一堆,对与我来说看了许久只想获取它的用法时,特意去整理一下.能快速使用并掌握它. 查看flag源码大致定义几下几种格式 //定义一个字符串的变量 type string ...
- c# 更新web.config
/// <summary> /// 添加和更新配置文件web.config的appSettings,缺点是会删除注释 /// </summary> /// <param ...
- SpringBoot配置中@ConfigurationProperties和@Value的区别
基本特征 @ConfigurationProperties 与@Bean结合为属性赋值 与@PropertySource(只能用于properties文件)结合读取指定文件 与@Validation结 ...
- 用vue-cli搭建vue项目
首先需要明确的是:Vue.js 不支持 IE8 及其以下 IE 版本,一般用与移动端,基础:开启最高权限的DOS命令(否则会出现意外的错误提示) 一.安装node.js,检测版本node -v,还要检 ...
- Spark之开窗函数
一.简介 开窗函数row_number()是按照某个字段分组,然后取另外一个字段排序的前几个值的函数,相当于分组topN.如果SQL语句里面使用了开窗函数,那么这个SQL语句必须使用HiveConte ...