LC329 - Longest Increasing Path in a Matrix
Problem
Example
Solution
Cached DFS
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
ROWS = len(matrix)
COLS = len(matrix[0])
@cache
def dfs(row, col, prev):
if (row < 0 or row == ROWS or col < 0 or col == COLS or matrix[row][col] <= prev):
return 0
subLip = 1
# Get LIP of each direction and return the maximum
subLip = max(subLip, 1 + dfs(row + 1, col, matrix[row][col]))
subLip = max(subLip, 1 + dfs(row - 1, col, matrix[row][col]))
subLip = max(subLip, 1 + dfs(row, col + 1, matrix[row][col]))
subLip = max(subLip, 1 + dfs(row, col - 1, matrix[row][col]))
return subLip
lip = 0
for row in range(ROWS):
for col in range(COLS):
# use -1 because value in each coord is >= 0
lip = max(lip, dfs(row, col, -1))
return lipLast updated