leetcode 787. Cheapest Flights Within K Stops(可以中转K次的航班)

LeetCode 787. Cheapest Flights Within K Stops(K站中转内最便宜的航班) 题目: 分析: 这题的思路是用递归来求解,因为每一步的判断都是类似的,比如找到下一个可以去的地方,然后把总价加上航班价格再把转站次数减一,递归,把这些修改后的参数作为新的参数。这题也有“剪枝”的思想,当总价大于当前更新的最小总价,那么就结束该方向的递归;或者是当前可转站次数为0,搜寻可直接到达的站点是否有目标站点,如果没有,则结束递归,如果有,就尝试更新最小总价。 解题过程: 特殊情况处理。 i... 阅读详情

There are n cities connected by m flights. Each flight 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:
在这里插入图片描述
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500

Constraints:

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.

给出一个有向图,求K次中转内起点到终点的最小cost。

思路:
(1) DFS
遍历每个起始点的下一终点,计算最小cost
可以用邻接链表,这里都放到HashMap里了
直接用DFS会超时,所以用dp数组记录已经计算过的结果

//17ms
class Solution {
    HashMap<Integer, HashMap<Integer, Integer>> map = new HashMap<>();
    Integer[][][] dp;
    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
        if(flights == null || flights.length == 0) {
            return -1;
        }
        
        dp = new Integer[n][n][K+1];
        for(int i = 0; i < flights.length; i++) {
            if(map.containsKey(flights[i][0])) {
                map.get(flights[i][0]).put(flights[i][1], flights[i][2]);
            } else {
                HashMap<Integer, Integer> tmp = new HashMap<>();
                tmp.put(flights[i][1], flights[i][2]);
                map.put(flights[i][0], tmp);
            }
        }
        
        return dfs(src, dst, K);
    }
    
    int dfs(int src, int dst, int K) {
        int result = Integer.MAX_VALUE;
        if(src == dst) {
            return 0;
        }
        if(dp[src][dst][K] != null) {
            return dp[src][dst][K];
        }
        if(map.containsKey(src)) {
            HashMap<Integer, Integer> prices = map.get(src);
            if(K == 0) {
                if(prices.containsKey(dst)) {
                    return prices.get(dst);
                } else {
                    return -1;
                }
            }
            
            for(Integer key : map.get(src).keySet()) {
                int tmp = dfs(key, dst, K-1);
                
                if(tmp >= 0) {
                    result = Math.min(result, map.get(src).get(key) + tmp);
                }               
            }
            
        } else {
            return -1;
        }
        
        result = (result == Integer.MAX_VALUE? -1 : result);
        dp[src][dst][K] = result;
        return result;
    } 
}

(2) DP
用dp[k][dst]表示经过k步到dst,如果看成k次中转的话,就是k+1步到dst
src == dst时,是不需要坐飞机的,所以dp[i][src] = 0
而dp[i][v] = min(dp[i][v], dp[i-1][u] + cost[u][v])
也就是说,经过i 步到v的cost,等于经过i - 1 步到达u站,再经过1步从u站到v站,在所有cost中选择最小的

因为最后结果是k次中转,所以取k+1步,dp[k+1][dst]

初始化inf = 1e9,这样当dp[k+1][dst] > inf 时返回-1

//4ms
    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
        if(flights == null || flights.length == 0) {
            return -1;
        }
        
        int inf = 100000000;
        
        int[][] dp = new int[K+2][n];
        for(int i = 0; i <= K+1; i++) {
            Arrays.fill(dp[i], inf);
            dp[i][src] = 0;
        }
        
        for(int i = 1; i <= K+1; i++) {
            for(int[] list : flights){
                dp[i][list[1]] = Math.min(dp[i][list[1]], 
                                          dp[i-1][list[0]] + list[2]);
            }
        }
        
        return dp[K+1][dst] >= inf ? -1 : dp[K+1][dst];
    }
科技英语/专业英语——改错总结【2】 1.固定句式 make it + adj + 句子 例:These features make the electronic systems difficult to intercept this kind of signal. 正确形式:These features make it  difficult for the electronic systems  to intercept 阅读详情

相关推荐

Windows10完美驱动Apple Studio Display:从雷电接口到亮度调节全攻略

本文详细介绍了如何在Windows10系统上完美驱动Apple Studio Display,涵盖雷电接口兼容性、亮度调节及色彩管理等关键问题。通过实测对比不同转接方案和显卡兼容性,推荐使用贝尔金VR线和NVIDIA GTX-1660显卡,并提供了BootCamp驱动安装和亮度调节的终极解决方案,帮助用户实现最佳显示效果。

elastic6hunter的博客 1142

LeetCode 787. K 站中转内最便宜的航班(图/Bellman Ford算法)

文章目录贝尔曼-福特算法(Bellman-Ford)简介算法思想算法执行过程应用题目描述分析代码LeetCode 787. K 站中转内最便宜的航班题目描述Bellman Ford + 邻接矩阵Reference 贝尔曼-福特算法(Bellman-Ford) 简介 贝尔曼-福特算法(Bellman-Ford)是由理查德·贝尔曼(Richard Bellman) 和 莱斯特·福特 创立的,求解含负权边的带权有向图的单源最短路径问题的一种算法。它的原理是对图进行V−1V-1V−1次松弛操作(VVV代表图中的点

xylitolz的博客 1614

通俗地解释一下 EMD(经验模态分解,Empirical Mode Decomposition)

EMD 就像把一碗“混在一起的面条”分成不同粗细的面条,方便你逐层分析每种波动。

qlkaicx的博客 1263

leetcode-787

最短路

qq_62999892的博客 350

【教程】BM1684X-32边缘计算盒子 网络配置教程

BM1684X边缘计算盒子网络配置教程

ShiMetaPi的博客 732

国科大学习资料--遥感原理集图像处理(尤红建)--2019年期末考试

国科大学习资料–遥感原理集图像处理(尤红建)–2019年期末考试 国科大学习资料–遥感原理集图像处理(尤红建)–2019年期末考试 国科大学习资料–遥感原理集图像处理(尤红建)–2019年期末考试 ================================================================== ================================================================== ==============

无名何许人的博客 1498

LeetCode第 787 题:K 站中转内最便宜的航班(C++)

787. K 站中转内最便宜的航班 - 力扣(LeetCode) 典型的dijkstra算法,几乎是固定优先级队列加上bfs(bfs求出的都是最大/最小)的思路了,这题多加了一个中转站的限制 不过我还是太年轻,代码并没有通过全部案例,第43个卡住了,主要问题是使用优先级队列的话,跳出循环的条件很难处理,k值和终点哪个作为判断依据暂时不明确。 class Solution { public: struct cmp{//按照距离排序 bool operator()(const pair&

zj 991

GEE数据融合——Landsat (collection 2,level 2 )4、5、7、8、9长时间序列影像数据融合和视频导出分析

长时间序列影像数据融合是指将Landsat影像数据集合2级2(Level 2)中的4、5、7、8和9这五个卫星的数据进行融合。具体来说,这包括将同一地点的多个卫星影像数据进行处理和整合,以产生一个单一的、具有更高质量的影像产品。在长时间序列影像数据融合中,首先需要对不同卫星的影像数据进行校正,以消除不同卫星之间的光谱差异、辐射度问题和几何纠正误差等。然后,通过使用融合算法,将多个卫星的影像数据进行组合,以生成一张全新的、高质量的合成影像。

此星光明博客 1743

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

K 站中转内最便宜的航班 有 n 个城市通过一些航班连接。给你一个数组 flights ,其中 flights[i] = [fromi, toi, pricei] ,表示该航班都从城市 fromi 开始,以价格 toi 抵达 pricei。 现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到出一条最多经过 k 站中转的路线,使得从 src 到 dst 的 价格最便宜 ,并返回该价格。 如果不存在这样的路线,则输出 -1。 示例 1: 输入: n = 3, edges = .

Tzecto 535

数据分析之AB测试基础知识

在 A/B 测试中,零假设是两组的指标是相同的,当假设检验推断出两组指标不同,但事实上两组指标相同时,就是第一类错误。

qq_45727498的博客 568

Python-增加b站视频播放量

如果条件允许的情况下,有代理API更好,每次请求url调用API也更方便。如果没有的话,也不用担心,网上本身也有着很多免费国内代理,不过代理是否可用需要自己花点时间去检测,检测方法笔者这里就不详述了,后面有时间的话会单独针对这一块做详细说明。在开始之前,需准备代理IP。总之,在每次请求url的时候,随机带入某个IP防止被平台检测,便于达到增加播放量预期。大致思路就是针对你的目标代理平台进行IP抓取,并存入到自己本地的IP代理池。本文是该专栏的第1篇,后面会持续更新对应平台干货知识,记得关注。

Python进阶专栏《爬虫实战进阶》,《Pyppeteer从入门到精通》原创作者 5237

【LeetCode】每日一题 2024_10_4 飞机座位分配概率(数学)

【【LeetCode】每日一题 2024_10_4 飞机座位分配概率(数学)】

Locky136的博客 699

汽车ECU诊断刷写和OTA升级中的验签和校验

汽车ECU诊断刷写和OTA升级中的验签和校验

天赐好车的博客 627

leetcode 787. Cheapest Flights Within K Stops

leetcode 787. Cheapest Flights Within K Stops leetcode 787. Cheapest Flights Within K Stops 题目描述 解答思路 代码 题目描述 There are n cities connected by m flights. Each fight starts from city u and ...

pjq的博客 1626

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

LeetCode 787. Cheapest Flights Within K Stops 题解

本题是图论中的最短路径问题。BFS 层序遍历,控制中转次数动态规划记录最低价格优先队列优化通过本题可以深入理解图的遍历和最短路径算法。

cannonjinx的博客 4301

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

LeetCode //C - 787. Cheapest Flights Within K Stops

Summary: The problem requires finding the cheapest flight path from a source city to a destination city with at most k stops. Using a modified Bellman-Ford algorithm, the solution iteratively relaxes all flight edges for k+1 iterations (representing k stop

Made in Code 1521

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Weekly Contest 72 leetcode 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 price w. Now given all the cities and fights, together with starting city src and the destinatio

淡然坊 968

LeetCode(787):K 站中转内最便宜的航班 Cheapest Flights Within K Stops(Java)

2019.7.18 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新) 这题是今年华为实习开发岗的笔试题,原题题干改成了蜜蜂采蜜的最短路径。 做法主要有两种: 1.最小堆+BFS 先将所有边的关系保存在二维数组edge中,将起始点加入最小堆,每次循环将最小堆中的最小值(当前花费最小的站)出堆作为当前结点curCity(如果curCity的步数超过K则重新出堆),遍历计算cur...

NJU_ChopinXBP的博客 1089

LeetCode——787. K 站中转内最便宜的航班(Cheapest Flights Within K Stops)[中等]——分析及代码(Java)

LeetCode——787. K 站中转内最便宜的航班[Cheapest Flights Within K Stops][中等]——分析及代码[Java]一、题目二、分析及代码1. 动态规划(1)思路(2)代码(3)结果三、其他 一、题目 有 n 个城市通过一些航班连接。给你一个数组 flights ,其中 flights[i] = [fromi, toi, pricei] ,表示该航班都从城市 fromi 开始,以价格 toi 抵达 pricei。 现在给定所有的城市和航班,以及出发城

江南土豆的博客 611

[leetcode] 787. Cheapest Flights Within K Stops

Description 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 dest...

Learning from the mistakes 469

leetcode 787. Cheapest Flights Within K Stops | 787. K 站中转内最便宜的航班(BFS)

题目 https://leetcode.com/problems/cheapest-flights-within-k-stops/ 题解 这题挺坑的实际上。DFS 超时了,因为涉及到步数限制 k,所以并不能加缓存,然后去看了答案。 答案给了一种 BFS 解法,看完思路我就开始一顿写。 一开始是按照如果走回头路的开销比不走回头路更小的话,就走回头路这种思路来写的。提交的时候发现,能不能走回头路,这个问题会比较复杂。 回头路是可以走的,但是不能简单的用回头路的开销去覆盖原有的开销,因为在你走回头路的时候,3步

寒泉 3万+

[Leetcode] 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 price w. Now given all the cities and fights, together with starting city src and the d

魔豆(Magicbean)的博客 1102

[leetcode] 787. Cheapest Flights Within K Stops @ python

原题 https://leetcode.com/problems/cheapest-flights-within-k-stops/ 解法 参考: [Java/Python] Priority Queue Solution 小根堆+BFS. 用字典储存flights中航班的信息, 然后每次从队列中取出第一个值便是符合题意的最小值, 当当前的城市等于目的地时, 返回价格, 否则遍历当前城市的下一站, ...

闲庭信步 343

leetcode - 787. Cheapest Flights Within K Stops

leetcode - 787

sinat_41679123的博客 640

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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/stren...

weixin_30538029的博客 150

LeetCode 787. Cheapest Flights Within K Stops?

There are n cities connected by m flights. Each flight 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 ds

Tech in Pieces 436
上一篇: leetcode 740. Delete and Earn(删除和赚硬币)
下一篇: leetcode 813. Largest Sum of Averages(最大平均数)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址