Browse curriculum

Longest Increasing Path in a Matrix (LeetCode 329)

Longest Increasing Path in a Matrix (LeetCode 329): find the longest strictly increasing path in a grid with DFS and memoisation: each cell's answer is 1 plus its best bigger neighbour, computed once.

Problem Understanding

Longest Increasing Path in a Matrix: given an m × n integer matrix, return the length of the longest strictly increasing path. From a cell you may move up, down, left or right, never diagonally or outside the grid.

Example: [[9,9,4],[6,6,8],[2,1,1]] returns 4, for the path 1 → 2 → 6 → 9.

The Intuition: Solve Each Cell Once

The best path starting at a cell is that cell plus the best path starting at one of its bigger neighbours. That gives a recursion:

  1. dfs(r, c) = 1 + max(dfs(neighbour)) over neighbours with a bigger value, or 1 if there are none.
  2. The answer for a cell never depends on the route that reached it, so memoise it: the second call returns instantly.
  3. A strictly increasing path cannot revisit a cell, so there are no cycles and no visited set is needed.

Every cell is solved once and looks at four neighbours, so the whole grid costs O(m · n). This is depth-first search on a grid, as in Number of Islands, combined with the caching of dynamic programming.

Longest Increasing Path in a Matrix Visualization

NUMBER UNDER A CELL = MEMO: LONGEST INCREASING PATH STARTING THERE

MEMO ALL 0

9

·

9

·

4

·

6

·

6

·

8

·

2

·

1

·

1

·

solved

0/9

longest

:

call stack (outermost first)

Empty

 

memo starts at 0 everywhere: no cell has been solved. Call dfs from every cell in turn

Next

dfs(0, 0) on 9: no bigger neighbour, so the path ends here

Free preview: the first 9 of 29 steps

matrix

Each cell shows its value with its memo underneath once solved. The running call is solid and the calls waiting on the stack are tinted. Try Snake to watch one call chain run through every cell, then every later call hit the memo.

Longest Increasing Path in a Matrix Dry Run

Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]. Final memo, the longest path starting at each cell:

col 0 col 1 col 2
row 0 9 → 1 9 → 1 4 → 2
row 1 6 → 2 6 → 2 8 → 1
row 2 2 → 3 1 → 4 1 → 2
  • memo(0, 2) = 2: 4 → 8.
  • memo(2, 1) = 4: 1 → 2 (memo 3) → 6 (memo 2) → 9 (memo 1).

Answer: 4.

Longest Increasing Path in a Matrix LeetCode Solution

Top-down DFS with a memo table. 0 in memo means not solved yet, since every real answer is at least 1.

Longest Increasing Path in a Matrix Code
1var longestIncreasingPath = function(matrix) {
2 const m = matrix.length, n = matrix[0].length;
3 const memo = Array.from({ length: m }, () => Array(n).fill(0));
4 const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
5 const dfs = (r, c) => {
6 if (memo[r][c]) return memo[r][c];
7 let best = 1;
8 for (const [dr, dc] of dirs) {
9 const nr = r + dr, nc = c + dc;
10 if (nr >= 0 && nr < m && nc >= 0 && nc < n && matrix[nr][nc] > matrix[r][c])
11 best = Math.max(best, 1 + dfs(nr, nc));
12 }
13 memo[r][c] = best;
14 return best;
15 };
16 let ans = 0;
17 for (let r = 0; r < m; r++)
18 for (let c = 0; c < n; c++) ans = Math.max(ans, dfs(r, c));
19 return ans;
20};

Longest Increasing Path in a Matrix in Python, Java, C++, TypeScript and C

Longest Increasing Path in a Matrix in Python
class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        m, n = len(matrix), len(matrix[0])
        memo = [[0] * n for _ in range(m)]
        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 < m and 0 <= nc < n and matrix[nr][nc] > matrix[r][c]:
                    best = max(best, 1 + dfs(nr, nc))
            memo[r][c] = best
            return best
        return max(dfs(r, c) for r in range(m) for c in range(n))
Longest Increasing Path in a Matrix in Java
class Solution {
    private static final int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public int longestIncreasingPath(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length, ans = 0;
        int[][] memo = new int[m][n];
        for (int r = 0; r < m; r++)
            for (int c = 0; c < n; c++)
                ans = Math.max(ans, dfs(matrix, memo, r, c));
        return ans;
    }

    private int dfs(int[][] matrix, int[][] memo, int r, int c) {
        if (memo[r][c] != 0) return memo[r][c];
        int best = 1;
        for (int[] d : DIRS) {
            int nr = r + d[0], nc = c + d[1];
            if (nr >= 0 && nr < matrix.length && nc >= 0 && nc < matrix[0].length && matrix[nr][nc] > matrix[r][c])
                best = Math.max(best, 1 + dfs(matrix, memo, nr, nc));
        }
        memo[r][c] = best;
        return best;
    }
}
Longest Increasing Path in a Matrix in C++
class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int m = matrix.size(), n = matrix[0].size(), ans = 0;
        vector<vector<int>> memo(m, vector<int>(n, 0));
        for (int r = 0; r < m; r++)
            for (int c = 0; c < n; c++)
                ans = max(ans, dfs(matrix, memo, r, c));
        return ans;
    }

private:
    int dfs(vector<vector<int>>& matrix, vector<vector<int>>& memo, int r, int c) {
        if (memo[r][c]) return memo[r][c];
        static const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        int best = 1;
        for (auto& d : dirs) {
            int nr = r + d[0], nc = c + d[1];
            if (nr >= 0 && nr < (int)matrix.size() && nc >= 0 && nc < (int)matrix[0].size() && matrix[nr][nc] > matrix[r][c])
                best = max(best, 1 + dfs(matrix, memo, nr, nc));
        }
        memo[r][c] = best;
        return best;
    }
};
Longest Increasing Path in a Matrix in TypeScript
function longestIncreasingPath(matrix: number[][]): number {
    const m = matrix.length, n = matrix[0].length;
    const memo: number[][] = Array.from({ length: m }, () => Array(n).fill(0));
    const dirs: number[][] = [[1, 0], [-1, 0], [0, 1], [0, -1]];
    const dfs = (r: number, c: number): number => {
        if (memo[r][c]) return memo[r][c];
        let best = 1;
        for (const [dr, dc] of dirs) {
            const nr = r + dr, nc = c + dc;
            if (nr >= 0 && nr < m && nc >= 0 && nc < n && matrix[nr][nc] > matrix[r][c])
                best = Math.max(best, 1 + dfs(nr, nc));
        }
        memo[r][c] = best;
        return best;
    };
    let ans = 0;
    for (let r = 0; r < m; r++)
        for (let c = 0; c < n; c++) ans = Math.max(ans, dfs(r, c));
    return ans;
}
Longest Increasing Path in a Matrix in C
static int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

int dfs(int** matrix, int m, int n, int* memo, int r, int c) {
    if (memo[r * n + c]) return memo[r * n + c];
    int best = 1;
    for (int k = 0; k < 4; k++) {
        int nr = r + dirs[k][0], nc = c + dirs[k][1];
        if (nr >= 0 && nr < m && nc >= 0 && nc < n && matrix[nr][nc] > matrix[r][c]) {
            int len = 1 + dfs(matrix, m, n, memo, nr, nc);
            if (len > best) best = len;
        }
    }
    memo[r * n + c] = best;
    return best;
}

int longestIncreasingPath(int** matrix, int matrixSize, int* matrixColSize) {
    int m = matrixSize, n = matrixColSize[0], ans = 0;
    int* memo = calloc(m * n, sizeof(int));
    for (int r = 0; r < m; r++)
        for (int c = 0; c < n; c++) {
            int len = dfs(matrix, m, n, memo, r, c);
            if (len > ans) ans = len;
        }
    free(memo);
    return ans;
}

Edge Cases & Common Mistakes

  • Equal neighbours: the path must be strictly increasing; >= would allow loops between equal cells.
  • No memo: plain DFS from every cell repeats the same sub-paths and is exponential on grids like the snake.
  • Adding a visited set: unnecessary, and if it is shared across calls it wrongly blocks later paths.
  • Single cell: the answer is 1.
  • Very large grids: recursion depth can reach m · n on a snake-shaped matrix; the topological-sort version avoids that.

Summary

dfs(r, c) returns 1 plus the best dfs of any bigger neighbour, cached in memo. Strict increase rules out cycles, so no visited set is needed. Call it from every cell and return the maximum. O(m · n) time and space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Define dfs(r, c)

    The longest strictly increasing path starting at (r, c). Return memo[r][c] if it is already set.

  2. Extend from bigger neighbours

    best = 1; for each of the four neighbours with a bigger value, best = max(best, 1 + dfs(neighbour)). Store best in memo.

  3. Try every start

    Call dfs from every cell and return the largest result.

Frequently asked questions

Why don't you need a visited set in Longest Increasing Path?

The path must be strictly increasing, so it can never return to a cell it has passed: that would need a value bigger than itself. With no cycles, the DFS cannot loop, and the memo table alone prevents repeated work.


Why does memoisation work here?

The longest increasing path starting at a cell depends only on the matrix, not on how you reached the cell. So dfs(r, c) always returns the same number; computing it once and storing it turns an exponential search into O(m · n).


Is there a non-recursive solution?

Yes. Treat each cell as a node with an edge to every bigger neighbour, then run a topological sort (Kahn's algorithm) peeling cells with no bigger neighbour layer by layer. The number of layers is the answer. It avoids deep recursion on large grids.

New to the technique behind this problem? Watch it run step by step:

Depth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description