Longest Increasing Path in a Matrix
Difficulty: Hard
Given a grid of integers, you can move from a cell to an adjacent one (up, down, left or right — no diagonals) if its value is strictly greater. Find the length, in cells, of the longest strictly increasing path, starting anywhere.
Examples
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
The path 1 -> 2 -> 6 -> 9 (bottom row up to top-left) has length 4, and nothing longer exists.
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
The path 3 -> 4 -> 5 -> 6 has length 4.
Constraints
1 <= rows, cols <= 200
0 <= matrix[i][j] <= 2^31 - 1
Approach
Let dp[r][c] be the length of the longest strictly increasing path starting at (r, c). It's 1 (the cell itself) plus the best dp among neighbors with a larger number — or just 1 if none is larger.
This is a depth-first search from each cell, but the same cells get visited by many searches. Increasing paths can't loop, so dp[r][c] never depends on itself. That makes it safe to cache each answer the first time and reuse it — turning an exponential search into one pass over every cell.
Solutions
Brute Force — DFS Without Memoization
From every cell, depth-first search through strictly larger neighbors, tracking the longest chain. Correct, but the same cell is re-explored from scratch by many searches.
function longestIncreasingPath(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
function dfs(r, c) {
let best = 1;
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && matrix[nr][nc] > matrix[r][c]) {
best = Math.max(best, 1 + dfs(nr, nc));
}
}
return best;
}
let answer = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
answer = Math.max(answer, dfs(r, c));
}
}
return answer;
}Time: Exponential in the worst case — the same cells get re-explored repeatedly · Space: O(rows * cols) — worst-case recursion depth
Optimal — DFS with a 2D Memo Table
The same depth-first search, but cache each cell's answer the first time. Later requests return instantly instead of re-searching.
function longestIncreasingPath(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
const cache = Array.from({ length: rows }, () => new Array(cols).fill(0));
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
function dfs(r, c) {
if (cache[r][c] !== 0) return cache[r][c];
let best = 1;
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && matrix[nr][nc] > matrix[r][c]) {
best = Math.max(best, 1 + dfs(nr, nc));
}
}
cache[r][c] = best;
return best;
}
let answer = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
answer = Math.max(answer, dfs(r, c));
}
}
return answer;
}Time: O(rows * cols) · Space: O(rows * cols) — for the cache and the recursion stack