原题链接在这里: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. 重置 Bootstrap modal 模态框数据

    利用 Bootstrap modal 模态框弹层添加或编辑数据,第二次弹出模态框时总是记住上一次的数据值,stackoverflow 上找到个比较好的方法,就是利用 jQuery 的 clone 方法 ...

  2. Python多进程方式抓取基金网站内容的方法分析

    因为进程也不是越多越好,我们计划分3个进程执行.意思就是 :把总共要抓取的28页分成三部分. 怎么分呢? # 初始range r = range(1,29) # 步长 step = 10 myList ...

  3. 进程池和线程池、协程、TCP单线程实现并发

    一.进程池和线程池 当被操作对象数目不大时,我们可以手动创建几个进程和线程,十几个几十个还好,但是如果有上百个上千个.手动操作麻烦而且电脑硬件跟不上,可以会崩溃,此时进程池.线程池的功效就能发挥了.我 ...

  4. vuex的Store简单使用过程

    介绍 Store的代码结构一般由State.Getters.Mutation.Actions这四种组成,也可以理解Store是一个容器,Store里面的状态与单纯的全局变量是不一样的,无法直接改变st ...

  5. C# 获取系统字体方法

    //需要引用命名空间 using System.Drawing; using System.Drawing.Text; //获取系统字体方法 public dynamic GetFontNames() ...

  6. virsh 添加虚拟交换机

    virsh 添加虚拟交换机 来源 https://blog.csdn.net/a1987463004/article/details/90905981 vim /etc/libvirt/qemu/ne ...

  7. 【转载】 C#中使用float.Parse方法将字符串转换为Float类型

    在C#编程过程中,很多时候涉及到数据类型的转换,例如将字符串类型的变量转换为单精度Float类型就是一个常见的类型转换操作,float.Parse方法是C#中专门用来将字符串转换为float类型的,f ...

  8. synchronized关键字的使用

    synchronized关键字是java并发编程中常使用的同步锁,用于锁住方法或者代码块,锁代码块时可以是synchronized(this){}.synchronized(Object){}.syn ...

  9. Github强制找回管理员账号密码

    步骤: 1. 登录Github所在的服务器,切换用户为git:su git 2. 进入Github的Rails控制台:gitlab-rails console production 3. 查看超级管理 ...

  10. centos7 docker安装nginx

    1.查询nginx最新镜像 docker search nginx 2.下载镜像 docker pull nginx 3.创建目录 mkdir -p /software/nginx/html mkdi ...