Longest Increasing Path in a Matrix
Difficulty: Hard · Pattern: Matrix · LeetCode #329
Return the length of the longest strictly increasing path in the matrix, moving in 4 directions (no diagonals, no wrap-around).
Examples
text
[[9,9,4],[6,6,8],[2,1,1]] → 4 (1 → 2 → 6 → 9)
[[3,4,5],[3,2,6],[2,2,1]] → 4 (3 → 4 → 5 → 6)Hints
- A path can't revisit a cell, because values strictly increase. So the "move to a larger neighbor" graph is a DAG.
- On a DAG, the longest path from a cell can be memoized:
lip(r,c) = 1 + max(lip(neighbor))over larger neighbors.
Approach
Memoized DFS: memo[r][c] = the longest increasing path starting at (r,c). Compute it once per cell, and each edge is examined once, so O(mn) total. No visited set is needed because cycles are impossible (strict increase).
Topological alternative (no recursion): compute out-degrees toward larger neighbors, BFS-peel the cells with out-degree 0 (the local maxima) layer by layer, and count the layers. This is useful in Python, where deep recursion can hit the recursion limit on a 200×200 grid.
Complexity
Time: O(m·n). Space: O(m·n).
Python solution
from functools import lru_cache
def longestIncreasingPath(matrix):
R, C = len(matrix), len(matrix[0])
@lru_cache(maxsize=None)
def lip(r, c):
best = 1
v = matrix[r][c]
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and matrix[nr][nc] > v:
best = max(best, 1 + lip(nr, nc))
return best
return max(lip(r, c) for r in range(R) for c in range(C))JavaScript solution
function longestIncreasingPath(matrix) {
// Topological peeling: repeatedly remove cells with no larger neighbor.
const R = matrix.length, C = matrix[0].length, dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
const out = Array.from({ length: R }, () => new Array(C).fill(0));
let layer = [];
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) {
for (const [dr, dc] of dirs) { const nr = r + dr, nc = c + dc; if (nr >= 0 && nc >= 0 && nr < R && nc < C && matrix[nr][nc] > matrix[r][c]) out[r][c]++; }
if (!out[r][c]) layer.push([r, c]);
}
let len = 0;
while (layer.length) {
len++;
const next = [];
for (const [r, c] of layer) for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < R && nc < C && matrix[nr][nc] < matrix[r][c] && --out[nr][nc] === 0) next.push([nr, nc]);
}
layer = next;
}
return len;
}