Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
nums = [ [9,9,4], [6,6,8], [2,1,1] ]
Return 4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
nums = [ [3,4,5], [3,2,6], [2,2,1] ]
Return 4
The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
/*algorithm: DFS+book
1)for each point<x,y>, check left,right,up,down
book the path,until not
2)update the longtest path
3)recursive call the above steps
example:
nums = [
[1,9,4],
[6,6,8],
[2,1,1]
]
*/
void dfs(vector<vector<int> >&matrix, vector<vector<int> >& paths,vector<vector<int> >&tbl,int m,int n,int x,int y){
if(x<0||x>=m||y<0||y>=n||tbl[x][y] || paths[x][y])return;
vector<int>dir(4,0);
tbl[x][y]=1;
if(y>0&&matrix[x][y] < matrix[x][y-1]){
if(!paths[x][y-1]){
dfs(matrix,paths,tbl,m,n,x,y-1);
}
dir[0]=paths[x][y-1];
}
if(x>0 && matrix[x][y] < matrix[x-1][y]){
if(!paths[x-1][y]){
dfs(matrix,paths,tbl,m,n,x-1,y);
}
dir[1]=paths[x-1][y];
}
if(y+1<n && matrix[x][y] < matrix[x][y+1]){
if(!paths[x][y+1]){
dfs(matrix,paths,tbl,m,n,x,y+1);
}
dir[2]=paths[x][y+1];
}
if(x+1<m && matrix[x][y] < matrix[x+1][y]){
if(!paths[x+1][y]){
dfs(matrix,paths,tbl,m,n,x+1,y);
}
dir[3]=paths[x+1][y];
}
int mValue=0;
for(int i = 0;i < 4;i++){
if(dir[i]>mValue)
mValue=dir[i];
}
paths[x][y] += 1+mValue;
tbl[x][y]=0;
}
int longestIncreasingPath(vector<vector<int> >& matrix) {
int maxPath = 0;
int m = matrix.size(),n = m?matrix[0].size():0;
vector<vector<int> >tbl(m,vector<int>(n,0));
vector<vector<int> > paths(m,vector<int>(n,0));
for(int i = 0;i < m;i++)
for(int j = 0;j < n;j++){
dfs(matrix,paths,tbl,m,n,i,j);
maxPath = max(maxPath,paths[i][j]);
}
return maxPath;
}
};