329. Longest Increasing Path in a Matrix
Hard
Given an m x n
integers matrix
, return the length of the longest increasing path in matrix
.
From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Example 1:
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Example 3:
Input: matrix = [[1]]
Output: 1
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
0 <= matrix[i][j] <= 231 - 1
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
self.matrix = matrix
self.rows = len(matrix)
self.cols = len(matrix[0])
self.dp = [[0] * self.cols for i in range(self.rows)]
result = 0
for i in range(self.rows):
for j in range(self.cols):
result = max(result, self.dfs(i,j))
return result
def dfs(self, row, col):
if not self.dp[row][col]:
self.dp[row][col] = 1 + max(
self.dfs(row-1, col) if row and self.matrix[row][col] < self.matrix[row-1][col] else 0,
self.dfs(row+1, col) if row+1 < self.rows and self.matrix[row][col] < self.matrix[row+1][col] else 0,
self.dfs(row, col-1) if col and self.matrix[row][col] < self.matrix[row][col-1] else 0,
self.dfs(row, col+1) if col+1 < self.cols and self.matrix[row][col] < self.matrix[row][col+1] else 0
)
return self.dp[row][col]
Last updated