当前位置:网站首页>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步最短路问题,优雅
边栏推荐
- register_ Chrdev and CDEV_ init cdev_ Add usage differences
- addmodule_allmerge_ams_im
- 八大基本排序(详解)
- 【JVM】一文带你了解JVM中的垃圾回收机制(GC)——内含图解
- nodejs学习笔记二
- 更多龙蜥自研特性!生产可用的 Anolis OS 8.6 正式发布
- Niuke: how many different binary search trees are there
- Go micro tutorial - Chapter 1 getting started
- 编译丨迅为iTOP4412开发板Makefile编译
- More dragon lizard self-developed features! Production available Anolis OS 8.6 officially released
猜你喜欢
AVIC UAV technology innovation board is listed: the fist product with a market value of 38.5 billion is pterodactyl UAV
【OpenCV 例程200篇】215. 基于多段线绘制近似椭圆
“推广+搞笑剧情”,如何碰撞出爆款的火花?
idea必用插件
More dragon lizard self-developed features! Production available Anolis OS 8.6 officially released
RT-Thread 堆区大小设置
Redis data structure analysis
7 月 2 日邀你来TD Hero 线上发布会
The meaning of linetypes enumeration values (line_4, line_8, line_aa) in opencv
居家办公浅谈远程协助快速提效心得 | 社区征文
随机推荐
RT-Thread 堆区大小设置
OpenCV中LineTypes各枚举值(LINE_4 、LINE_8 、LINE_AA )的含义
Anaconda下安装Jupyter notebook
Pref usage record
Redis elimination strategy
addmodule_ allmerge_ ams_ im
List becomes vector list becomes vector list vector
异常类_日志框架
Niuke.com: minimum cost of climbing stairs
The meaning of linetypes enumeration values (line_4, line_8, line_aa) in opencv
阿里云盘分享压缩包
9: Chapter 3: e-commerce engineering analysis: 4: [general module]; (to be written...)
更多龙蜥自研特性!生产可用的 Anolis OS 8.6 正式发布
【微信小程序】小程序的宿主环境
《网络是怎么样连接的》读书笔记 - 汇总篇
How to connect the Internet Reading Notes - Summary
Additional: (not written yet, don't look at ~ ~ ~) webmvcconfigurer interface;
Tencent two sides: @bean and @component are used on the same class. What happens?
IO stream_ recursion
The 25th anniversary of Hong Kong's return to China the Hong Kong Palace Museum officially opened as a new cultural landmark