题目描述
题目大意
题目大意求二维矩阵中最长的递增路径。
思路
和417. Pacific Atlantic Water Flow非常类似,直接DFS求解。一般来说DFS需要有固定的起点,但是对于这个题,二维矩阵中的每个位置都算作起点。
把每个位置都当做起点,然后去做个dfs,看最长路径是多少。然后再找出全局的最长路径。使用动态规划dp保存已经访问过的位置,这样能节省了很多搜索的过程,然后有个continue是为了剪枝。因为这个做法比较暴力,就没有什么好讲的了。
代码
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
def DFS(x, y):
val = matrix[x][y]
if not dp[x][y]:
dp[x][y] = 1 + max(
DFS(x - 1, y) if x and val < matrix[x - 1][y] else 0,
DFS(x, y - 1) if y and val < matrix[x][y - 1] else 0,
DFS(x + 1, y) if x < N-1and val < matrix[x + 1][y] else 0,
DFS(x, y + 1) if y < M-1 and val < matrix[x][y + 1] else 0
)
return dp[x][y]
if (matrix == None or not matrix ):
return 0
N = len(matrix)
M = len(matrix[0])
dp = [[0] * M for i in range(N)]
maxpath = 0
for i in range(N):
for j in range(M):
maxpath = max(maxpath, DFS(i, j))
return maxpath