给定一个整数矩阵,找出最长递增路径的长度。
对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
示例 1:
输入: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
输出: 4
解释: 最长递增路径为 [1, 2, 6, 9]。
示例 2:
输入: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
输出: 4
解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
DFS
from functools import lru_cache
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
if not matrix:
return 0
m = len(matrix)
n = len(matrix[0])
dicts = [
(-1, 0),
(1, 0),
(0, -1),
(0, 1)
]
#无需用缓存矩阵记录是否被遍历过了
@lru_cache(None)
def dfs(i, j):
#这设置为1,表示只要进入了dfs,那么这个点已经在路径中了
num = 1
for x,y in dicts:
newX = i+x
newY = j+y
if 0<=newX<m and 0<=newY<n and matrix[newX][newY] > matrix[i][j]:
#这部分dfs+1可以想作以5为起点,开始5进入dfs返回num = max(num, dfs(6)+1)
#dfs(6)因为周围没有比他大的元素,所以返回1.最终以5为起点的最长路径长度为2.这样就可理解了
num = max(num, dfs(newX, newY)+1)
return num
res = 0
for i in range(m):
for j in range(n):
#最初i=0, j=0
#每次遍历完一个点都会更新res,最终取所有点最大的
res = max(res, dfs(i, j))
return res