classSolution:deflongestIncreasingPath(self, matrix: List[List[int]])->int:ifnot matrix:return0
h,w =len(matrix),len(matrix[0])
store =[[None]*(w)for i inrange(h)]
m =0#储存max路径值defsearch_nearby(i,j):nonlocal m
compare =[]#储存可以比较的候选人#这个楼主很懒,还没想怎么简化下面的代码#反正下面四个代码块就是分别看一下上、下、左、右哪些格子的值可以当做候选人比较#上if i !=0and matrix[i-1][j]< matrix[i][j]:#有上边且上边小于当前数的话
compare.append(store[i-1][j])if store[i-1][j]else compare.append(search_nearby(i-1,j))#左if j !=0and matrix[i][j-1]< matrix[i][j]:#有左边且左边小于当前数的话
compare.append(store[i][j-1])if store[i][j-1]else compare.append(search_nearby(i,j-1))#下if i != h-1and matrix[i+1][j]< matrix[i][j]:#有下边且下边小于当前数的话
compare.append(store[i+1][j])if store[i+1][j]else compare.append(search_nearby(i+1,j))#右if j != w-1and matrix[i][j+1]< matrix[i][j]:#有右边且右边小于当前数的话
compare.append(store[i][j+1])if store[i][j+1]else compare.append(search_nearby(i,j+1))
store[i][j]=max(compare)+1if compare else1#如果没有compare说明这是一个很小的数,是一个起始点,能组成的长度只有1#有的话就原来最长路径+1
m =max(m,store[i][j])return(store[i][j])for i inrange(h):for j inrange(w):ifnot store[i][j]:
search_nearby(i,j)return m
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可# 递增路径的最大长度# @param matrix int整型二维数组 描述矩阵的每个数# @return int整型classSolution:deflongestIncreasingPath(self, matrix: List[List[int]])->int:# write code here
row =len(matrix)
col =len(matrix[0])
temp =[[0]* col for _ inrange(row)]defdfs(i, j):# 以matrix[i][j]为起点的最长递增路径长度
res =1for x,y in[(i-1,j),(i+1,j),(i,j-1),(i,j+1)]:# 若不越界 且 当前值大于前一个值(递增)if0<=x<row and0<=y<col and matrix[x][y]> matrix[i][j]:# 若未遍历过,则进行深度遍历获得最长路径值if temp[x][y]==0:
res =max(res,dfs(x,y)+1)# 若已经遍历过,则直接取出值来获得最长路径值else:
res =max(res,temp[x][y]+1)
temp[i][j]= res # 记录当前位置的最长路径值return res
ans =1for i inrange(row):for j inrange(col):
ans =max(ans,dfs(i,j))return ans