Skip to main content

329. Longest Increasing Path in a Matrix

hard

Return the length of the longest path of strictly increasing values in a matrix, where moves are to 4-directional neighbors. The strict-increase rule makes the path graph acyclic — that's what unlocks memoized DFS over the grid.

By Sam K., Founder, InterviewChamp.AI · Last verified

Problem

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).

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2^31 - 1

Examples

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

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Ctrl+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Strict increase means edges only go from smaller to larger — no cycles. Every cell has a well-defined longest path starting from it.

Hint 2

Memoize dfs(i, j) = 1 + max over strictly-larger neighbors of dfs(neighbor).

Hint 3

Iterate every cell, return the global max. Each cell is computed once.

Hint 4

Alternative: topological sort by cell value, then relax distances on the DAG — same big-O.

Solution approach

Reveal approach

Memoized DFS. dp[i][j] caches the length of the longest strictly-increasing path starting at (i, j). For each cell, recursively explore its four neighbors; recurse only into neighbors whose value is strictly greater. dp[i][j] = 1 + max over valid neighbors of dp[neighbor]. Iterate every starting cell and return the global max. Because strict increase forbids cycles, each cell is visited and memoized exactly once. An alternative is topological-order DP: sort all cells by value ascending, then relax each cell's two smaller-or-equal neighbors' dp into the cell. Both run in O(m * n) time and O(m * n) space.

Complexity

Time
O(m * n)
Space
O(m * n)

Related patterns

  • dynamic-programming
  • memoization
  • grid-dp
  • dfs

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

More 2D Dynamic Programming practice problems

See all 2D Dynamic Programming problems →