当前位置:网站首页>leetcode:329. 矩阵中的最长递增路径【dfs + cache + 无需回溯 + 优雅】
leetcode:329. 矩阵中的最长递增路径【dfs + cache + 无需回溯 + 优雅】
2022-07-01 12:35:00 【白速龙王的回眸】

分析
为什么不用visit,因为是严格递增序列,所以一定不存在还能回头走的情况,所以无需visit
然后思路也是一样,遍历每个起点
dfs返回的是最大长度,记录的参数包括当前的位置,以及前一个数的位置
由于我们遍历的是起点,所以天然的,前一个数的位置就是所选的起点
然后由于如果我们固定了当前的位置,以及前一个数的大小,这个能走的最大距离也是固定的
因此可以记忆化
这里面的核心代码就是,把现在的难题丢给下一步(下一步满足条件)
res = max(res, dfs(nr, nc, matrix[nr][nc]) + 1)
ac code
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
maxn = 0
# dfs + memory优雅
# 当点和上一个点固定,它能走的最大长度也就固定
@cache
def dfs(r, c, pre):
res = 1 # 最少也是当前这个点
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < m and 0 <= nc < n and matrix[nr][nc] > pre:
res = max(res, dfs(nr, nc, matrix[nr][nc]) + 1)
return res
ans = 0
# 遍历每个起点获得不同起点的最大值
for i in range(m):
for j in range(n):
ans = max(ans, dfs(i, j, matrix[i][j]))
return ans
总结
二维图求最什么的路径啥的
可以考虑dfs + cache
dfs记录的是啥,参数是啥,输出是啥
什么时候能进入下一个dfs
上一个dfs和下一个dfs有什么关系
需要visit防止重复吗
需要回溯吗。。。
边栏推荐
- redis探索之缓存击穿、缓存雪崩、缓存穿透
- Nc100 converts strings to integers (ATOI)
- Circular linked list--
- Like the three foot platform
- Tencent security and KPMG released a regulatory technology white paper to analyze the "3+3" hot application scenarios
- codeforces -- 4B. Before an Exam
- ANSI/UL 94 VTM薄质材料垂直燃烧测试
- 栈的应用——括号匹配问题
- 被锡膏坑了一把
- Eurake分区理解
猜你喜欢

Onenet Internet of things platform - create mqtts products and devices

2022-06-28-06-29

本科毕业四年:工作,辞职,结婚,买房

Typora adds watermarks to automatically uploaded pictures

Onenet Internet of things platform - mqtt product devices send messages to message queues MQ

Onenet Internet of things platform - mqtts product equipment connected to the platform

【20220605】文献翻译——虚拟现实中的可视化:一个系统的回顾

Typora realizes automatic uploading of picture pasting

The operation process of using sugar to make a large data visualization screen

Indefinite integral
随机推荐
Machine learning - Data Science Library Day 3 - Notes
Application of stack -- bracket matching problem
Powerful, easy-to-use, professional editor / notebook software suitable for programmers / software developers, comprehensive evaluation and comprehensive recommendation
Onenet Internet of things platform - mqtt product equipment upload data points
【20211129】Jupyter Notebook远程服务器配置
[speech signal processing] 3 speech signal visualization -- prosody
队列操作---
系统测试UI测试总结与问题(面试)
Chapter 14 signals (IV) - examples of multi process tasks
System test UI test summary and questions (interview)
MySQL common functions
[shell programming] - shell introductory learning
华为面试题: 招聘
栈-------
Relationship between accuracy factor (DOP) and covariance in GPS data (reference link)
Onenet Internet of things platform - mqtts product equipment connected to the platform
关于NAND FLASH解扣的认识
下半年还有很多事要做
[datawhale202206] pytorch recommendation system: recall model DSSM & youtubednn
[106] 360 check font - check whether the copyright of local Fonts is commercially available