当前位置:网站首页>leetcode:787. K 站中转内最便宜的航班【k步最短路 + dfs记忆化 + defaultdict(dict)】
leetcode:787. K 站中转内最便宜的航班【k步最短路 + dfs记忆化 + defaultdict(dict)】
2022-06-30 15:49:00 【白速龙王的回眸】

ac code
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
# k站中转,可以走k + 1次
connect = defaultdict(dict) # 二维dict
for x, y, c in flights:
connect[x][y] = c
# 只能走k步的dfs
# 自顶向下
@cache
def dfs(now, remain):
# 成功退出
if now == dst:
return 0
# 到达步数,无限远
if remain == 0:
return inf
remain -= 1
res = inf
# 遍历下一个位置
for nxt in connect[now]:
res = min(res, dfs(nxt, remain) + connect[now][nxt])
return res
ans = dfs(src, k + 1)
return ans if ans != inf else -1
分析
用一个defaultdict记录每一个点能飞到的地方和距离
自顶向下的dfs + cache
记忆化参数是当前的位置以及剩余的次数,结果是到达终点的距离
如果能到达终点,返回0
如果次数用尽,返回inf
次数-1,且当前res设置为inf
遍历所有能飞的下一个位置,然后res取res和dfs(nxt, remain) + connect[now][nxt]的最小值
这种思想就是把问题推到下一步,直到尽头(到达终点,次数用尽)
总结
dfs解决k步最短路问题,优雅
边栏推荐
- Lambda expression_ Stream stream_ File class
- On July 2, I invited you to TD Hero online conference
- 山西化工园区智能化管控平台建设时间表
- [Verilog quick start of Niuke online question series] ~ bit splitting and operation
- 香港回归25周年 香港故宫博物馆正式开放成文化新地标
- Bc1.2 PD protocol
- 几个跨端开发神器
- 2020 Blue Bridge Cup group B - move bricks - (greedy sorting +01 backpack)
- 深度学习——(2)几种常见的损失函数
- 【OpenCV 例程200篇】215. 基于多段线绘制近似椭圆
猜你喜欢

Raft introduction
![删除有序数组中的重复项 II[双指针--多情况统一]](/img/e2/cadfdbe476a86cb2d72c1ae0160a4a.png)
删除有序数组中的重复项 II[双指针--多情况统一]

Redis elimination strategy

Rong Lianyun launched rphone based on Tongxin UOS to create a new ecology of localization contact center

【JVM】一文带你了解JVM中的垃圾回收机制(GC)——内含图解

深度学习——(2)几种常见的损失函数

八大基本排序(详解)

【JVM】类加载相关面试题——类加载过程、双亲委派模型

更多龙蜥自研特性!生产可用的 Anolis OS 8.6 正式发布
![[Verilog basics] summary of some concepts about clock signals (clock setup/hold, clock tree, clock skew, clock latency, clock transition..)](/img/54/fd7541dae4aad7e4216bcaabbb146b.png)
[Verilog basics] summary of some concepts about clock signals (clock setup/hold, clock tree, clock skew, clock latency, clock transition..)
随机推荐
Research on helmet wearing detection algorithm
2022 Blue Bridge Cup group B -2022- (01 backpack to calculate the number of schemes)
Hologres shared cluster helps Taobao subscribe to the extreme refined operation
Anaconda下安装Jupyter notebook
Additional: (not written yet, don't look at ~ ~ ~) webmvcconfigurer interface;
idea必用插件
[bjdctf2020]the mystery of ip|[ciscn2019 southeast China division]web11|ssti injection
山西化工园区智能化管控平台建设时间表
AVIC UAV technology innovation board is listed: the fist product with a market value of 38.5 billion is pterodactyl UAV
互联网研发效能实践之去哪儿网(Qunar)核心领域DevOps落地实践
[wechat applet] the hosting environment of the applet
restartProcessIfVisible的流程
聊聊远程办公那些事儿 | 社区征文
Niuke.com: minimum cost of climbing stairs
Halcon knowledge: regional topics [07]
IndexSearch
In order to make remote work unaffected, I wrote an internal chat room | community essay
Etcd教程 — 第八章 Etcd之Compact、Watch和Lease API
异常类_日志框架
Redis data structure analysis