题目:
给定一个整数矩阵,找出最长递增路径的长度。
对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
示例 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,在遍历的时候用矩阵记录以当前坐标为起点的最长递增序列。
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
h = len(matrix)
if h==0:
return 0
w = len(matrix[0])
max_length = 1
length = [[-1]*w for i in range(h)]
for i in range(h):
for j in range(w):
if length[i][j]!=-1:
max_length = max(max_length, length[i][j])
else:
l = self.lengthIncreasingPathe(matrix, i, j, w, h, length)
max_length = max(max_length, l)
print(length)
return max_length
def lengthIncreasingPathe(self, matrix, i, j, w, h, length):
if length[i][j]!=-1:
return length[i][j]
dindex = [[0,1], [0,-1],[1, 0], [-1, 0]]
l = 1
for [dx, dy] in dindex:
x = i+dx
y = j+dy
if x>=0 and x<h and y>=0 and y<w:
if matrix[x][y]>matrix[i][j]:
l = max(self.lengthIncreasingPathe(matrix, x, y, w, h, length)+1, l)
length[i][j] = l
return l