AlgoMaster Logo

Longest Increasing Path in a Matrix

hardFrequency7 min readUpdated June 23, 2026

Understanding the Problem

We have a 2D grid of integers, and we need to find the longest path where each step moves to a strictly larger value. Movement is restricted to the four cardinal directions (up, down, left, right), no diagonals.

The path must be strictly increasing, so it can never revisit a cell: a cell's value cannot be strictly greater than itself. That eliminates cycles. The implicit graph formed by "cell A has an edge to cell B if B is an adjacent cell with a larger value" is a Directed Acyclic Graph (DAG), and finding the longest path in a DAG can be solved with dynamic programming or a topological ordering.

The path can also start and end at any cell, so every cell is a potential starting point and the answer is the maximum over all of them.

Key Constraints:

  • 1 <= m, n <= 200 -> The matrix has at most 40,000 cells, so an O(m * n) solution runs well within limits.
  • 0 <= matrix[i][j] <= 2^31 - 1 -> Values reach the top of the signed 32-bit range. The code only compares values, never sums them, so a 32-bit int is safe and there is no overflow risk.
  • Strictly increasing -> No cycles in the movement graph, which is what makes the DP and topological approaches valid.

Approach 1: Brute Force DFS

Intuition

Try every cell as a starting point and explore all increasing paths from it with DFS. From a cell, look at all four neighbors and recurse into any neighbor with a strictly larger value. The longest path starting from a cell is 1 (the cell itself) plus the maximum path length among its valid neighbors.

Without caching, the same subproblems get recomputed repeatedly. If cell (0, 0) leads to cell (1, 0), and cell (0, 1) also leads to cell (1, 0), the entire subtree rooted at (1, 0) is explored twice. In the worst case this is exponential.

Algorithm

  1. For each cell (i, j) in the matrix, run a DFS to find the longest increasing path starting from that cell.
  2. In the DFS, explore all four directions. For each neighbor with a strictly larger value, recursively compute the path length.
  3. Return 1 + max of all valid neighbor path lengths.
  4. Track the global maximum across all starting cells.

Example Walkthrough

1Try each cell as a starting point. Begin DFS from (2,1)=1.
0
1
2
0
9
9
4
1
6
6
8
2
2
start
1
1
1/6

Code

The brute force recomputes the same cell's longest path every time it is reached from a different predecessor. The next approach computes each cell's result once and caches it.

Approach 2: DFS with Memoization

Intuition

The brute force recomputes paths from cells it has already fully explored, so add a cache. Define dp[i][j] as the length of the longest increasing path starting from cell (i, j). The first time DFS computes it, store the value. Every future call for the same cell returns the cached value in O(1).

With memoization, each cell is computed once. The DFS from a cell visits at most 4 neighbors, and each neighbor either returns a cached value or triggers a computation that happens only once. The total work across all DFS calls is O(m * n).

Algorithm

  1. Create a 2D array dp of size m x n, initialized to 0 (0 means "not yet computed").
  2. For each cell (i, j), call dfs(i, j).
  3. In dfs(i, j): if dp[i][j] is already computed (non-zero), return it. Otherwise, explore all four neighbors with strictly larger values, recursively compute their path lengths, and set dp[i][j] = 1 + max of all valid neighbor results.
  4. Return the maximum value in dp.

Example Walkthrough

matrix
1Start DFS from (2,1)=1. Its larger neighbors are (2,0)=2 and (1,1)=6.
0
1
2
0
9
9
4
1
6
6
8
2
2
start
1
1
dp
1dp grid initialized to 0 (0 means not yet computed).
0
1
2
0
0
0
0
1
0
0
0
2
0
0
0
1/7

Code

The DFS with memoization is optimal in time, but its recursion stack can be as deep as m * n, which risks a stack overflow on a 200 x 200 grid that forms one long path. The next approach processes cells iteratively using a topological ordering, avoiding deep recursion.

Approach 3: BFS Topological Sort (Peeling)

Intuition

Instead of DFS, use BFS with a topological ordering (Kahn's algorithm). Define each cell's in-degree as the count of adjacent cells with strictly smaller values. Cells with in-degree 0 are local minima and form the first BFS layer. Process layer by layer: for each processed cell, decrement the in-degree of every larger neighbor, and when a neighbor's in-degree reaches 0, add it to the next layer. The number of layers processed equals the longest increasing path.

Algorithm

  1. Compute the in-degree of each cell. A cell's in-degree is the number of adjacent cells with a strictly smaller value.
  2. Add all cells with in-degree 0 to the BFS queue (these are local minima).
  3. Process the BFS level by level. For each cell in the current level, check all four neighbors. If a neighbor has a strictly larger value, decrement its in-degree. If it drops to 0, add it to the next level.
  4. Count the number of BFS levels processed. That is the answer.

Example Walkthrough

matrix
1Compute in-degrees. Cells with in-degree 0: (0,0)=3, (1,1)=2, (2,0)=2, (2,2)=1
0
1
2
0
deg=0
3
4
5
1
3
deg=0
2
6
2
deg=0
2
2
deg=0
1
inDegree
1Initial in-degrees. Cells with 0: (0,0), (1,1), (2,0), (2,2)
0
1
2
0
queue
0
2
1
1
2
queue
0
3
2
queue
0
1
queue
0
1/6

Code