Longest Increasing Path in a Matrix
Hard
Topics
Given an m x n integer matrix, return the length of the longest strictly increasing path. From a cell you may move up, down, left, or right (no diagonals or wrap-around).
Example 1
The shaded chain is a longest strictly increasing walk, length 4.
2D grid — one row per line.
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] Output: 4 Explanation: The path [1,2,6,9].
Example 2
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]] Output: 4
Constraints
- 1 <= m, n <= 200
- 0 <= matrix[i][j] <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
Because you can only step to strictly larger values, the graph of moves is a DAG — no cycles. So the longest path from each cell is well-defined and can be memoized.
Approach
- Define
dfs(r,c)= longest increasing path starting at that cell. - It is 1 plus the max
dfsover neighbours with a strictly greater value. - Cache each result; the answer is the max over all starting cells.
Dry Run
grid = [[9, 9, 4],
[6, 6, 8],
[2, 1, 1]]
dfs fills memo[r][c] = longest increasing path STARTING at that cell.
Visited in row-major order; each cell is computed once and then reused.
(0,0)=9 no larger neighbour memo 1
(0,1)=9 no larger neighbour memo 1
(0,2)=4 8 is larger -> dfs(1,2) = 1 memo 2
(1,0)=6 9 is larger -> memo[0][0] = 1 reused memo 2
(1,1)=6 9 gives 1, 8 gives 1 memo 2
(2,0)=2 6 is larger -> memo[1][0] = 2 reused memo 3
(2,1)=1 6 gives 2, and 2 gives 3 memo 4
(2,2)=1 8 is larger -> memo[1][2] = 1 reused memo 2
final memo = [[1, 1, 2],
[2, 2, 1],
[3, 4, 2]]
answer 4 (the path 1 -> 2 -> 6 -> 9 up the left side, from (2,1))
Note what is absent: no visited set and no cycle check. Movement is only ever
to a STRICTLY larger value, so a cycle is impossible by construction -- which
is what lets plain memoisation stand in for a topological order here.Complexity
- Time — O(m*n): each cell is computed once thanks to memoization.
- Space — O(m*n): the memo table plus recursion stack.
Common Pitfalls
- Without memoization this is exponential — the cache is what makes it linear in cells.
Full Solution — all languages
class Solution:
def longestIncreasingPath(self, grid):
R,C=len(grid),len(grid[0])
memo=[[0]*C for _ in range(R)]
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<R and 0<=nc<C and grid[nr][nc]>grid[r][c]:
best=max(best,1+dfs(nr,nc))
memo[r][c]=best
return best
return max(dfs(r,c) for r in range(R) for c in range(C))import java.util.*;
class Solution {
public int longestIncreasingPath(int[][] grid) {
int R=grid.length,C=grid[0].length;
int[][] memo=new int[R][C];
int ans=0;
for(int r=0;r<R;r++)for(int c=0;c<C;c++)ans=Math.max(ans,dfs(grid,memo,r,c));
return ans;
}
int dfs(int[][] g,int[][] memo,int r,int c) {
if(memo[r][c]!=0)return memo[r][c];
int R=g.length,C=g[0].length;
int best=1;
int[] dr={1,-1,0,0},dc={0,0,1,-1};
for(int d=0;d<4;d++) {
int nr=r+dr[d],nc=c+dc[d];
if(nr>=0&&nr<R&&nc>=0&&nc<C&&g[nr][nc]>g[r][c])best=Math.max(best,1+dfs(g,memo,nr,nc));
}
memo[r][c]=best;
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestIncreasingPath(vector<vector<int>>& grid) {
int R=grid.size(),C=grid[0].size();
vector<vector<int>> memo(R,vector<int>(C,0));
int dr[]={1,-1,0,0},dc[]={0,0,1,-1};
function<int(int,int)> dfs=[&](int r,int c)->int {
if(memo[r][c])return memo[r][c];
int best=1;
for(int d=0;d<4;d++) {
int nr=r+dr[d],nc=c+dc[d];
if(nr>=0&&nr<R&&nc>=0&&nc<C&&grid[nr][nc]>grid[r][c])best=max(best,1+dfs(nr,nc));
}
memo[r][c]=best;
return best;
};
int ans=0;
for(int r=0;r<R;r++)for(int c=0;c<C;c++)ans=max(ans,dfs(r,c));
return ans;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var longestIncreasingPath = function(grid) {
const R=grid.length,C=grid[0].length,memo=[];
for(let i=0;i<R;i++)memo.push(new Array(C).fill(0));
const dirs=[[1,0],[-1,0],[0,1],[0,-1]];
function dfs(r,c) {
if(memo[r][c])return memo[r][c];
let best=1;
for(const d of dirs) {
const nr=r+d[0],nc=c+d[1];
if(nr>=0&&nr<R&&nc>=0&&nc<C&&grid[nr][nc]>grid[r][c])best=Math.max(best,1+dfs(nr,nc));
}
memo[r][c]=best;
return best;
}
let ans=0;
for(let r=0;r<R;r++)for(let c=0;c<C;c++)ans=Math.max(ans,dfs(r,c));
return ans;
};