一.题目:
给一个矩阵,里面都是数字,求矩阵中存在的最长递增路径的长度.
Example 1:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
二.解题思路:
这种题一开始感觉是要用递归去做的,设计递归函数dfs(matrix,i,j)表示以矩阵matrix的i,j位置的元素结尾的最长递增路径的长度.
初步代码如下:
def dfs(matrix, i ,j):
m,n = len(matrix),len(matrix[0])
res = 1
dirs = [[0,1],[0,-1],[-1,0],[1,0]]
for dx,dy in dirs:
if dx+i>=0 and dx+i < m and dy+j>=0 and dy+j<n and matrix[i][j] > matrix[dx+i][dy+j]:
path = dfs(matrix,dx+i,dy+j) +1
res = max(path,res)
return res
结果发现超时了,稍微想一想就知道在上面这个递归函数中会进行很多重复的递归,为了解决这个问题我们可以建立一个cache矩阵,用来表示在某些位置我们已经计算了他的最长递增路径长度,所以新的递归函数代码如下:
def dfs(matrix, i ,j, cache):
m,n = len(matrix),len(matrix[0])
if cache[i][j] != 0:
return cache[i][j]
res = 1
dirs = [[0,1],[0,-1],[-1,0],[1,0]]
for dx,dy in dirs:
if dx+i>=0 and dx+i < m and dy+j>=0 and dy+j<n and matrix[i][j] > matrix[dx+i][dy+j]:
path = dfs(matrix,dx+i,dy+j,cache) +1
res = max(path,res)
cache[i][j] = res
return res
最终整体的代码也出来了:
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
#DFS
def dfs(matrix, i ,j, cache):
m,n = len(matrix),len(matrix[0])
if cache[i][j] != 0:
return cache[i][j]
res = 1
dirs = [[0,1],[0,-1],[-1,0],[1,0]]
for dx,dy in dirs:
if dx+i>=0 and dx+i < m and dy+j>=0 and dy+j<n and matrix[i][j] > matrix[dx+i][dy+j]:
path = dfs(matrix,dx+i,dy+j,cache) +1
res = max(path,res)
cache[i][j] = res
return res
max_len = 1
if matrix ==[]:
return 0
m,n = len(matrix),len(matrix[0])
cache = [[0] * n for i in range(m)]
for i in range(m):
for j in range(n):
#计算matrix中i,j所在位置的元素的递增路径长度
max_len = max(max_len, dfs(matrix,i,j,cache))
return max_len