Longest Increasing Path In A Matrix Problem
Description
LeetCode Problem 329.
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] <= 2^31 - 1
Solution
Approach: DFS with Memoization
A plain DFS from every cell explores the same paths again and again, which can take exponential time. The key observation is that the answer for a cell does not depend on how we reached it: the longest increasing path starting at (r, c) is always the same. So compute it once and store it.
Let longest[r][c] be the length of the longest increasing path that starts at (r, c):
longest[r][c] = 1 + max(longest[nr][nc]) over the neighbors with matrix[nr][nc] > matrix[r][c], or 1 if there is no larger neighbor.
dfs(r, c)returns the stored value if it has been computed (0 means "not yet").- Otherwise it tries the four neighbors, recursing only into strictly larger ones, stores the best length, and returns it.
- The answer is the largest
dfs(r, c)over all cells.
We need no visited set. Every step goes to a strictly larger value, so a path can never come back to a cell, and the recursion cannot loop. That is also why memoizing is safe: when dfs(r, c) finishes, its value is final.
The detail people get wrong is using >= instead of >: equal neighbors are not an increasing step, and allowing them would create cycles (for example between two cells that both hold 7).
Complexity: O(m · n) time and O(m · n) space, where m and n are the numbers of rows and columns: each cell is computed once and looks at four neighbors. The recursion can go as deep as the longest path.
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
rows, cols = len(matrix), len(matrix[0])
# longest[r][c] = length of the longest increasing path that starts at (r, c); 0 means not computed yet.
longest = [[0] * cols for _ in range(rows)]
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
def dfs(r: int, c: int) -> int:
if longest[r][c] > 0:
return longest[r][c]
best = 1 # the path made of this cell alone
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > matrix[r][c]:
best = max(best, 1 + dfs(nr, nc))
longest[r][c] = best
return best
answer = 0
for r in range(rows):
for c in range(cols):
answer = max(answer, dfs(r, c))
return answer
Now write it from memory
Close the write-up and solve it yourself against the tests.