15% off all plans & roadmaps Use code

See plans

Longest Increasing Path in a Matrix

Updated

TL;DR: Find the longest chain of orthogonally adjacent cells whose values strictly increase. Treat each cell as a node in an acyclic graph and compute the longest path ending at every cell once, in value order.

Problem

You are given an integer grid matrix. Two cells are adjacent when one sits directly above, below, left, or right of the other. Diagonal moves are not allowed.

A path can start at any cell. Each move must go to an adjacent cell whose value is strictly greater than the current one. The path length is the number of cells visited, including the first. Return the length of the longest such path. Paths cannot leave the grid, and a single cell is always a path of length 1.

Example 1

Input: matrix = [[-3,-2,-1],[4,3,0],[5,6,7]]
Output: 9
Explanation: Visit -3, -2, -1, 0, 3, 4, 5, 6, 7 in that order. Every consecutive pair is adjacent and strictly increasing.

Example 2

Input: matrix = [[7,7],[7,7]]
Output: 1
Explanation: Equal values cannot be used for a move, so every path has length 1.

Example 3

Input: matrix = [[12,1,2,3],[11,10,9,4]]
Output: 8
Explanation: One longest path is 1 → 2 → 3 → 4 → 9 → 10 → 11 → 12.

Constraints

  • 1 <= matrix.length <= 200
  • 1 <= matrix[0].length <= 200
  • All rows in matrix have the same length.
  • -2^31 <= matrix[row][column] <= 2^31 - 1
  • matrix contains at least one cell.

Constraints that matter

  • The grid has up to 200 * 200 = 40,000 cells. A search that re-explores shared paths can blow up exponentially, so each cell's answer must be computed once.
  • Moves need strictly greater values, so the cell graph has no cycles. That is what makes a DP or a topological order valid.
  • Values span the full 32-bit range. Compare them directly, and in Java or C# avoid subtracting two values in a sort comparator because the difference can overflow.
  • A path can be 40,000 cells long, so plain recursion can overflow the stack in Python, JavaScript, Java and C#. An iterative method avoids that risk.
  • Every cell is a legal start, so the answer is the maximum over all cells, not the value at one corner.

View on LeetCode

Hints

Hint 1

This is dynamic programming on a grid, but the order of the subproblems is not row by row.

Hint 2

Start a depth-first search at every cell.

Solution

Intuition

This is dynamic programming on a grid, but the order of the subproblems is not row by row. Define best(cell) as the longest increasing path that ends at that cell. It equals 1 plus the maximum best over adjacent cells with a smaller value, or 1 if no neighbor is smaller.

Picture a row of dominoes where each one can only fall after the lower neighbors touching it have fallen. Each cell is a domino, the indegree is how many lower neighbors still stand, and each round knocks down the dominoes with none left.

What points to DP is the repeated work. Many starting cells can reach the same middle cell, and the longest path from that cell is the same no matter how you got there. Strictness is the second clue. A move always goes to a larger value, so you can never return to a cell.

The grid is therefore an acyclic graph, and any acyclic graph has an order in which every cell comes after all its predecessors. Two such orders are easy to get. Sorting the cells by value gives one, because every predecessor of a cell has a smaller value. Counting smaller neighbors and peeling off cells with none gives the other, which is Kahn's topological sort.

A third option is a depth-first search that caches each cell's result, called memoization. It computes the same table but uses recursion, and the recursion can reach 40,000 frames deep.

This page ends on the peeling version. It does O(R * C) work and needs no recursion. The number of peeling rounds is the answer directly. You also do not need a visited array, because the strictly increasing rule already prevents loops.

Watch the pattern animation

Worked example

Input: matrix = [[12, 1, 2, 3], [11, 10, 9, 4]]
Output: 8
Explanation: The grid has 8 cells, and they can all be chained in increasing order: 1, 2, 3, 4, 9, 10, 11, 12. Each step moves to an adjacent cell. The chain winds along the top row, down the right side, and back along the bottom row, so every cell is used.

Approach 1: Brute force DFS from every cell

Start a depth-first search at every cell. From a cell, try each of the four neighbors with a larger value and take the best result plus 1. The answer is the maximum over all starting cells.

There is no memory. Each call recomputes the longest path from its cell, even if an earlier call already did.

Steps

  1. Define dfs(r, c) that returns the longest increasing path starting at (r, c).
  2. Set best = 1 for the cell itself.
  3. For each of the four neighbors inside the grid with a strictly larger value, compute 1 + dfs(neighbor) and keep the maximum.
  4. Return best.
  5. Call dfs for every cell and return the largest result.

Dry run

Run on [[12,1,2,3],[11,10,9,4]]. Start at the cell holding 1. Its larger neighbors are 12, 2 and 10, so the search tries all three.

The branch through 2 tries 3 and 9. The branch through 3 goes to 4, then 9, then 10, then 11, then 12, giving 8 cells from 1. The branch 2 → 9 → 10 → 11 → 12 gives only 6 cells.

Note that dfs(9) runs once from 2 and again from 4. Each run walks 9 → 10 → 11 → 12 from scratch. The start at 1 returns 8, and no other start beats it, so the answer is 8.

Complexity

TimeExponential: O(R * C * 3^(R * C)) loose upper bound
SpaceO(R * C)

Let R and C be the rows and columns. A path has at most R * C cells, and after the first move a call has at most 3 larger neighbors to try, which gives the loose bound above. It is not tight, but the true worst case is still exponential.

Take a grid where matrix[r][c] = r + c. Every cell has a larger neighbor to the right and below. The number of paths from the top-left cell to the opposite corner is a binomial coefficient that grows exponentially with grid size.

The recursion depth is at most the longest path, so space is O(R * C).

PythonTested in our runner

import sys
from typing import List, Optional

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        sys.setrecursionlimit(100000)
        rows, cols = len(matrix), len(matrix[0])
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))

        def dfs(r: int, c: int) -> int:
            best = 1
            for dr, dc in dirs:
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > matrix[r][c]:
                    best = max(best, 1 + dfs(nr, nc))
            return best

        answer = 0
        for r in range(rows):
            for c in range(cols):
                answer = max(answer, dfs(r, c))
        return answer

Approach 2: Sort by value, then DP

What's slow: the brute force recomputes the same cell many times. In the example, dfs(9) ran twice and walked the same tail each time.

The insight that fixes it: handle cells from smallest value to largest. When you reach a cell, every smaller neighbor is already finished. Keep dp[cell] as the longest path ending there, starting at 1. When you process a cell, push its value forward: for each larger neighbor, set dp[neighbor] = max(dp[neighbor], dp[cell] + 1).

Each cell is finalized exactly once. This is the same table that a memoized DFS would fill, built bottom-up with no recursion.

Steps

  1. Create a list of all cell indices and sort it by the cell's value, ascending.
  2. Create dp with every entry set to 1.
  3. Walk the sorted list. For each cell, update the global best with dp[cell].
  4. For each of its four neighbors with a strictly larger value, set dp[neighbor] = max(dp[neighbor], dp[cell] + 1).
  5. Return the best value seen.

Dry run

Run on [[12,1,2,3],[11,10,9,4]]. Sorted values are 1, 2, 3, 4, 9, 10, 11, 12. All dp entries start at 1.

  • Process 1 (dp 1): neighbors 12, 2 and 10 become 2.
  • Process 2 (dp 2): 3 becomes 3 and 9 becomes 3. The neighbor 1 is smaller and is skipped.
  • Process 3 (dp 3): 4 becomes 4.
  • Process 4 (dp 4): 9 becomes 5, replacing 3.
  • Process 9 (dp 5): 10 becomes 6.
  • Process 10 (dp 6): 11 becomes 7.
  • Process 11 (dp 7): 12 becomes 8.
  • Process 12 (dp 8): no larger neighbors.

The largest dp is 8, which is the answer.

Complexity

TimeO(R * C * log(R * C))
SpaceO(R * C)

Let N = R * C. Sorting N cells costs O(N log N). The sweep visits each cell once and checks four neighbors, which is O(N).

The sort dominates, so time is O(N log N). The dp array and the sorted index list each hold N entries, so space is O(N).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        rows, cols = len(matrix), len(matrix[0])
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
        # cell index = r * cols + c, sorted by value ascending
        order = sorted(range(rows * cols), key=lambda i: matrix[i // cols][i % cols])
        dp = [1] * (rows * cols)
        best = 1
        for cell in order:
            r, c = divmod(cell, cols)
            best = max(best, dp[cell])
            for dr, dc in dirs:
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > matrix[r][c]:
                    nxt = nr * cols + nc
                    dp[nxt] = max(dp[nxt], dp[cell] + 1)
        return best
2D Array (Unique Paths on Grid) pattern infographic for Longest Increasing Path in a Matrix

Solution pattern

2D Array (Unique Paths on Grid)

Part of Dynamic Programming (DP) Patterns

Approach 3: Topological sort by layers (Kahn)Optimal2D Array (Unique Paths on Grid)

What's slow: sorting spends O(N log N) to build an order that the grid already contains. Each cell only needs to wait for its smaller neighbors.

The insight that fixes it: count, for each cell, how many neighbors are smaller. That count is its indegree. Cells with indegree 0 are local minima, so each starts a path of length 1. Process them as layer 1.

Finishing a cell lowers the indegree of each larger neighbor by one. A neighbor reaches 0 only after its last smaller neighbor is done, so it lands in the layer after its deepest predecessor.

Layer k holds exactly the cells whose longest path ending there has k cells. The number of layers is the answer, and no DP array is needed.

Why it is correct. A cell joins layer k only after every smaller neighbor has already left an earlier layer. So its layer number is one more than its deepest smaller neighbor, which matches the recurrence best(cell) = 1 + max over smaller neighbors. Since every cell is eventually removed, the last layer number is the largest best value, which is the answer.

Steps

  1. For every cell, count the adjacent cells with a smaller value and store it in indegree.
  2. Put every cell with indegree 0 into the current layer.
  3. While the current layer is not empty, add 1 to length.
  4. For each cell in the layer, visit each larger neighbor and decrease its indegree by 1.
  5. When a neighbor's indegree reaches 0, add it to the next layer.
  6. Make the next layer the current layer and repeat. Return length when no layers remain.

Dry run

Run on [[12,1,2,3],[11,10,9,4]]. The indegrees are: 12 has 2 (neighbors 1 and 11), 1 has 0, 2 has 1, 3 has 1, 11 has 1 (neighbor 10), 10 has 2 (neighbors 1 and 9), 9 has 2 (neighbors 2 and 4), 4 has 1 (neighbor 3). Only the cell with 1 starts at 0.

LayerCells processedIndegree changesNext layer
1112: 2 to 1, 2: 1 to 0, 10: 2 to 12
223: 1 to 0, 9: 2 to 13
334: 1 to 04
449: 1 to 09
5910: 1 to 010
61011: 1 to 011
71112: 1 to 012
812noneempty

The loop ran for 8 layers, so length = 8, which matches the expected output.

Complexity

TimeO(R * C)
SpaceO(R * C)

Let N = R * C. Building the indegrees checks four neighbors per cell, which is 4N comparisons. Each cell enters a layer exactly once, because it joins only when its indegree hits 0 and the grid has no cycles.

Processing a cell checks four neighbors, so the layer work is also 4N. Total time is O(N). The indegree array and the layer lists hold at most N entries, so space is O(N).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        rows, cols = len(matrix), len(matrix[0])
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
        indegree = [[0] * cols for _ in range(rows)]
        for r in range(rows):
            for c in range(cols):
                for dr, dc in dirs:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] < matrix[r][c]:
                        indegree[r][c] += 1

        # layer 1 holds cells with no smaller neighbor
        current = [(r, c) for r in range(rows) for c in range(cols) if indegree[r][c] == 0]
        length = 0
        while current:
            length += 1
            nxt = []
            for r, c in current:
                for dr, dc in dirs:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > matrix[r][c]:
                        indegree[nr][nc] -= 1
                        if indegree[nr][nc] == 0:
                            nxt.append((nr, nc))
            current = nxt
        return length

Common mistakes

  • Using a visited array in the DFS. Strictly increasing moves cannot revisit a cell, so a visited set adds nothing, and if you clear it wrongly it can block valid paths. Drop it and compare values instead.
  • Using matrix[nr][nc] >= matrix[r][c] for the move test. Equal values must not be a legal move, so with [[7,7],[7,7]] the answer would be wrong or the recursion would never end. Use a strict >.
  • Calling the search or the layer loop from only one corner. A path can start at any cell, so run it from every cell, or seed Kahn with every cell of indegree 0.
  • Forgetting the + 1 for the current cell, as in best = max(best, dfs(next)). The path length counts cells, so each step adds one. Use 1 + dfs(next) and start best at 1.
  • Sorting with (a, b) -> matrix[a] - matrix[b] in Java or C#. Values near -2^31 and 2^31 - 1 overflow the subtraction and give a wrong order. Use Integer.compare or Array.Sort(keys, items).
  • Checking matrix[nr][nc] before the bounds test, as in matrix[nr][nc] > x && nr >= 0. That reads outside the grid. Test nr and nc against the bounds first.
  • Memoizing with a recursive DFS and trusting the default stack. A snake-shaped 200 by 200 grid has a path of 40,000 cells, which overflows Python, JavaScript, Java and C# stacks. Use an iterative order such as sort or Kahn.

Edge cases

  • A 1 by 1 matrix such as [[5]] returns 1, since a lone cell is a path of length 1.
  • All cells equal, such as [[7,7],[7,7]], returns 1. No move is allowed, and every cell has indegree 0.
  • A single row or single column with increasing values, such as [[1,2,3,4]], returns the full length 4.
  • A single row that decreases, such as [[4,3,2,1]], returns 4, because you can walk it right to left.
  • Extreme values such as [[-2147483648, 2147483647]] return 2. Safe comparisons matter here, and subtraction would overflow.
  • A 200 by 200 snake that visits every cell in increasing order returns 40,000. This tests stack depth in recursive code and speed in brute force.

Follow-ups interviewers ask

Why not use DFS with memoization, and does it work here?
It works and has the same O(R * C) time. Cache the result of each cell in a table and return it when you see the cell again. The catch is recursion depth, which can reach 40,000 on a snake-shaped grid. In languages with small stacks you either raise the limit or switch to the sort or Kahn version.
How would you return the actual path, not just its length?
Record a parent for each cell when you update its dp value in the sort version. Remember which cell gave the maximum. Then find the cell with the largest dp, follow parents back to a cell with no parent, and reverse the list. This adds O(R * C) space for the parent array and no extra time.
What changes if diagonal moves are allowed, or if the path may be non-strict?
Diagonals only enlarge the neighbor list from four to eight, and the complexity stays O(R * C). Non-strict moves break the method. Equal neighbors could point at each other, which creates cycles. The longest path would become unbounded without a visited rule, and the problem turns into a much harder one.

Longest Increasing Path in a Matrix FAQ

What is the time complexity of Longest Increasing Path in a Matrix?

The best solutions run in O(R * C), where R and C are the rows and columns. Memoized DFS and Kahn topological sort each handle every cell once and check four neighbors. Sorting the cells first costs O(R * C log(R * C)). Plain DFS without caching is exponential.

Why use dynamic programming for Longest Increasing Path in a Matrix?

The longest path ending at a cell depends only on its smaller neighbors, and many starting cells share the same sub-paths. Storing one answer per cell removes the repeated work. Because moves are strictly increasing, the cells have a natural order, so the DP has no cycles to worry about.

Can Longest Increasing Path in a Matrix be solved in O(1) extra space?

Not in any known practical way. Every approach needs a per-cell value, either a memo, a dp entry or an indegree, so it uses O(R * C) extra space. Writing into the input would hide the extra array. It would still be O(R * C), and the problem says to leave the input unchanged.

Why is there no visited array in the Longest Increasing Path in a Matrix solution?

Each move goes to a strictly larger value, so a path can never return to a cell it already used. No cycle can exist. A visited array would only add bugs, such as blocking a cell that a different path legitimately reaches.

How does the Kahn topological sort give the answer in Longest Increasing Path in a Matrix?

Each layer of the queue holds cells whose longest path ending there has the same number of cells. Layer 1 has cells with no smaller neighbor. A cell joins layer k + 1 when its last smaller neighbor is in layer k. The count of layers is the length of the longest path.

Is the LeetCode 329 recursive solution safe in Python or JavaScript?

Not on the largest inputs. A long snake-shaped path can need 40,000 nested calls, which exceeds default limits in Python and JavaScript and can overflow the stack in Java and C#. The sort and Kahn versions on this page use loops, so depth is never an issue.

Asked at

See which companies ask this — Pro

Practise it