Longest Increasing Path in a Matrix

Hard

Topics
GraphDFSDynamic ProgrammingMatrixMemoization

Given an m x n integer matrix, return the length of the longest strictly increasing path. From a cell you may move up, down, left, or right (no diagonals or wrap-around).

Example 1

099416682211012
The shaded chain is a longest strictly increasing walk, length 4.
2D grid — one row per line.
Input:  matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The path [1,2,6,9].

Example 2

034513262221012
Input:  matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4

Constraints

  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

Because you can only step to strictly larger values, the graph of moves is a DAG — no cycles. So the longest path from each cell is well-defined and can be memoized.

Approach

  1. Define dfs(r,c) = longest increasing path starting at that cell.
  2. It is 1 plus the max dfs over neighbours with a strictly greater value.
  3. Cache each result; the answer is the max over all starting cells.

Dry Run

grid = [[9, 9, 4],
         [6, 6, 8],
         [2, 1, 1]]

dfs fills memo[r][c] = longest increasing path STARTING at that cell.
Visited in row-major order; each cell is computed once and then reused.

(0,0)=9  no larger neighbour                      memo 1
(0,1)=9  no larger neighbour                      memo 1
(0,2)=4  8 is larger -> dfs(1,2) = 1              memo 2
(1,0)=6  9 is larger -> memo[0][0] = 1 reused     memo 2
(1,1)=6  9 gives 1, 8 gives 1                     memo 2
(2,0)=2  6 is larger -> memo[1][0] = 2 reused     memo 3
(2,1)=1  6 gives 2, and 2 gives 3                 memo 4
(2,2)=1  8 is larger -> memo[1][2] = 1 reused     memo 2

final memo = [[1, 1, 2],
              [2, 2, 1],
              [3, 4, 2]]

answer 4   (the path 1 -> 2 -> 6 -> 9 up the left side, from (2,1))

Note what is absent: no visited set and no cycle check. Movement is only ever
to a STRICTLY larger value, so a cycle is impossible by construction -- which
is what lets plain memoisation stand in for a topological order here.

Complexity

  • Time — O(m*n): each cell is computed once thanks to memoization.
  • Space — O(m*n): the memo table plus recursion stack.

Common Pitfalls

  • Without memoization this is exponential — the cache is what makes it linear in cells.

Full Solution — all languages

class Solution:
    def longestIncreasingPath(self, grid):
        R,C=len(grid),len(grid[0])
        memo=[[0]*C for _ in range(R)]
        def dfs(r,c):
            if memo[r][c]: return memo[r][c]
            best=1
            for dr,dc in ((1,0),(-1,0),(0,1),(0,-1)):
                nr,nc=r+dr,c+dc
                if 0<=nr<R and 0<=nc<C and grid[nr][nc]>grid[r][c]:
                    best=max(best,1+dfs(nr,nc))
            memo[r][c]=best
            return best
        return max(dfs(r,c) for r in range(R) for c in range(C))
Asked at DoorDash Nutanix
SensAI
Beta
Tap the mic to stop voice mode