Date and Time: Dec 25, 2024, 23:46 (EST)
Link: https://leetcode.com/problems/longest-increasing-path-in-a-matrix
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
-
m == matrix.length
-
n == matrix[i].length
-
1 <= m, n <= 200
-
0 <= matrix[i][j] <= 2^31 - 1
-
Build 2D DP as cache for each entry's Longest Increasing Path.
-
Run DFS from each entry to their neighbors to find their Longest Increasing Path, update
dp[r][c] = 1 + max_path
.
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
# Build 2D DP to cache each entry's longest increasing path
# Run DFS from each entry to find the entry's neighbors' LIP + 1
# TC: O(m*n), m=rows, n=cols, SC: O(m*n)
rows, cols = len(matrix), len(matrix[0])
dp = [[0] * cols for _ in range(rows)]
directions = [[-1, 0], [1, 0], [0, 1], [0, -1]]
res = 0
# Save the result into dp, and return dp[r][c]
def dfs(r, c):
if not dp[r][c]:
max_path = 0
for dr, dc in directions:
row, col = dr+r, dc+c
if row in range(rows) and col in range(cols) and matrix[row][col] > matrix[r][c]:
max_path = max(max_path, dfs(row, col))
dp[r][c] = 1 + max_path
return dp[r][c]
for r in range(rows):
for c in range(cols):
res = max(res, dfs(r, c))
return res
Time Complexity: $O(mn)$
Space Complexity: $O(mn)$