Longest Increasing Path in a Matrix (LeetCode 329): Solution and Explanation

Hard
Array
Dynamic Programming
Depth First Search
Breadth First Search
Graph
Topological Sort
Memoization
Matrix

Given a grid of integers, find the length of the longest path where each step moves up, down, left or right to a strictly larger value. Paths can start anywhere, and diagonal moves or wrapping around the edges are not allowed.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force runs a DFS from every cell, exploring every strictly increasing path and keeping the longest. Each DFS can branch four ways at every step, so without any reuse the total work can grow exponentially on grids with long increasing snakes.

Two observations rescue it. First, because every step must go to a strictly larger value, a path can never return to a cell it already visited. The moves form a directed acyclic graph, which means there is no need for a visited set during the DFS and no risk of infinite loops. Second, the longest increasing path starting from a given cell does not depend on how you arrived at that cell. It only depends on the cell itself.

So the answer for each cell can be computed once and cached. Define dfs(r, c) as the length of the longest increasing path that starts at (r, c). It is 1 plus the best dfs among the neighbors with larger values, or just 1 if there are none. With a memo table, every cell is solved exactly once, and the final answer is the maximum over all cells. This is DP on a DAG, written top-down.

Approach: DFS with memoization

  1. Return 0 for an empty matrix, then create a memo table of zeros the same size as the grid.
  2. Define dfs(r, c): if memo[r][c] is non-zero, return it, since every real path length is at least 1.
  3. Start with max_len = 1, the path containing only this cell.
  4. For each of the four neighbors that is in bounds and has a strictly larger value, update max_len = max(max_len, 1 + dfs(nr, nc)).
  5. Store max_len in memo[r][c] and return it.
  6. Return the maximum of dfs(r, c) over every cell.

Step-by-step example

matrix = [[9,9,4],[6,6,8],[2,1,1]]
  1. dfs(0, 0) on 9 has no larger neighbor, so it is 1. The same holds for the other 9 and for the 8 at (1, 2).
  2. dfs(0, 2) on 4 can step to 9 or to 8, both worth 1, so it is 2.
  3. dfs(1, 0) on 6 can step up to 9, so it is 2. dfs(1, 1) on the middle 6 can step to 9 or 8, also 2.
  4. dfs(2, 0) on 2 can step up to 6 at (1, 0), so it is 1 + 2 = 3.
  5. dfs(2, 1) on 1 can step to 2 (worth 3) or to 6 (worth 2), so it is 1 + 3 = 4. The last 1 at (2, 2) can step to 8 for a value of 2.
  6. The maximum over all cells is 4, the path 1, 2, 6, 9.

Code: Python, Java, C++

1class Solution:
2    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
3        if not matrix:
4            return 0
5
6        m, n = len(matrix), len(matrix[0])
7        memo = [[0] * n for _ in range(m)]
8
9        def dfs(r, c):
10            if memo[r][c]:
11                return memo[r][c]
12
13            directions = [(0,1),(0,-1),(1,0),(-1,0)]
14            max_len = 1
15            for dr, dc in directions:
16                nr, nc = r + dr, c + dc
17                if 0 <= nr < m and 0 <= nc < n and matrix[nr][nc] > matrix[r][c]:
18                    max_len = max(max_len, 1 + dfs(nr, nc))
19
20            memo[r][c] = max_len
21            return max_len
22
23        return max(dfs(r, c) for r in range(m) for c in range(n))

Time and space complexity

Time

O(m × n)

Each cell's value is computed once thanks to the memo, and each computation checks four neighbors. Later calls for the same cell return immediately.

Space

O(m × n)

The memo table has one entry per cell, and the recursion stack can be as deep as the longest path, which is at most m × n.

Other approaches

Topological sort by peeling (BFS) (time O(m × n), space O(m × n))

Compute each cell's out-degree toward larger neighbors, start a queue with cells that have no larger neighbor and peel layers inward. The number of layers is the answer. It avoids deep recursion on large grids.

Sort cells by value (time O((m × n) log(m × n)), space O(m × n))

Process cells from largest value to smallest, setting each cell's answer from its already processed larger neighbors. Simple to reason about, but the sort adds a log factor.

Common mistakes

  • Adding a visited set and backtracking as if paths could loop; strictly increasing moves already prevent cycles, and the extra state breaks memoization.
  • Using non-strict comparison (>=), which allows moves between equal values, creates cycles and gives wrong answers or infinite recursion.
  • Memoizing based on the path so far instead of only the cell, which makes the cache useless.
  • Hitting Python's default recursion limit on a large grid that is one long increasing snake; raise the limit or switch to the peeling BFS.

Frequently asked questions

Why doesn't the DFS need a visited set?

Every step goes to a strictly larger value, so you can never return to an earlier cell on the same path. The grid moves form a directed acyclic graph.

Why does memoization work here?

The longest increasing path starting from a cell depends only on that cell and the grid, not on how you reached it. So each cell's answer can be computed once and reused.

What is the time complexity of longest increasing path in a matrix?

O(m × n). Each cell is solved once with constant work for its four neighbors, and cached results return immediately.

Can it be solved without recursion?

Yes. Treat the grid as a DAG and run Kahn-style topological sorting, peeling off cells with no larger neighbors layer by layer. The number of layers equals the longest path.