Longest Increasing Path in a Matrix
Given an m x n grid of integers, return the length of the longest strictly increasing path in it.
From each cell you can move up, down, left or right. You can't move diagonally or outside the grid, and each step must go to a strictly larger value.
Example 1
Input: matrix = [[9, 9, 4], [6, 6, 8], [2, 1, 1]] Output: 4
The longest increasing path is 1 → 2 → 6 → 9.
Example 2
Input: matrix = [[3, 4, 5], [3, 2, 6], [2, 2, 1]] Output: 4
The longest increasing path is 3 → 4 → 5 → 6. Moving diagonally isn't allowed.
Constraints
1 <= m, n <= 2000 <= matrix[i][j] <= 2^31 - 1
Approach
Running a fresh depth-first search from every cell explores the same paths again and again, which takes exponential time on a grid like a snake of increasing values. The key fact is that the longest increasing path starting at a cell depends only on that cell: it's 1 plus the best answer among neighbors with a larger value. Since values strictly increase, those neighbors can never lead back to the current cell, so the dependencies have no cycles.
That makes the search safe to cache. Compute the answer for a cell once, store it, and every later search that reaches the cell reuses it. Then take the largest answer over all cells.
Steps
- Create a cache with one entry per cell.
- Define
longest_from(r, c): start at1, and for each neighbor with a larger value, try1 + longest_from(neighbor). Cache and return the best result. - Call
longest_fromfor every cell and return the maximum.
import sys
from functools import lru_cache
from typing import List
def longest_increasing_path(matrix: List[List[int]]) -> int:
rows, cols = len(matrix), len(matrix[0])
sys.setrecursionlimit(max(1000, rows * cols + 100)) # a path can be m * n cells long
@lru_cache(maxsize=None)
def longest_from(r: int, c: int) -> int:
# the answer for a cell never depends on how you reached it, so it is cached
best = 1
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
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 + longest_from(nr, nc))
return best
return max(longest_from(r, c) for r in range(rows) for c in range(cols))Complexity
- Time:
O(m · n). Each cell is computed once and checks four neighbors. - Space:
O(m · n)for the cache and the recursion stack. On a snake-shaped grid the recursion can gom · ncalls deep, which the iterative version in the challenge avoids.
Common mistakes
- Keeping a visited set and clearing it between searches. It isn't needed because a strictly increasing path can't repeat a cell, and clearing it throws away the work you could have reused.
- Allowing equal neighbors. The path must strictly increase, so
7 → 7isn't a valid step. - Only starting from the smallest value in the grid. The longest path can start anywhere, so check every cell.