SDE & MLE Prep

329. Longest Increasing Path in a Matrix

Problem

Return the length of the longest strictly increasing path in matrix, moving up, down, left or right (no diagonals, no wrapping).

Example: [[9,9,4],[6,6,8],[2,1,1]] → 4 (1 → 2 → 6 → 9)

Constraints: up to 200 × 200.

Strictly increasing paths can't cycle, so the grid is a DAG: best(r, c) = 1 + max(best(neighbor) for larger neighbours), memoized.

Complexity: O(R·C).

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        R, C = len(matrix), len(matrix[0])

        @cache
        def best(r, c):
            v, res = matrix[r][c], 1
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < R and 0 <= nc < C and matrix[nr][nc] > v:
                    res = max(res, 1 + best(nr, nc))
            return res

        return max(best(r, c) for r in range(R) for c in range(C))