Longest Increasing Path in a Matrix
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.
求以每个点为起点求满足条件的最长递增路径,对每个点的求法是求大于当前点的周围四个点中为起点的最大值+1为当前点的最长路径。
代码:
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
if (matrix.empty())
return 0;
int row=matrix.size();
int col=matrix[0].size();
int ans=0;
vector<vector<int>>vis(row,vector<int>(col,0));
for (int i=0; i<row; i++)
{
for (int j=0; j<col; j++)
{
int res=0;
dfs(matrix,i,j,res,vis);
ans=max(ans,res);
}
}
return ans;
}
void dfs(vector<vector<int>>&matrix,int row,int col,int &res,vector<vector<int>>&vis)
{
if (vis[row][col])
{
res=vis[row][col];
return ;
}
int dx[4]={0,1,0,-1};
int dy[4]={-1,0,1,0};
int height=matrix.size();
int width=matrix[0].size();
int sum=0;
int maxsizhou=0;
for (int i=0; i<4; i++)
{
int posy=row+dy[i];
int posx=col+dx[i];
if (posy<0||posy>=height||posx<0||posx>=width)
continue;
if (matrix[posy][posx]<=matrix[row][col])
{
continue;
}
sum++;
if (vis[posy][posx])
{
maxsizhou=max(maxsizhou,vis[posy][posx]);
// res=max(res,vis[posy][posx]+1);
}
else
{
int tempres=0;
dfs(matrix,posy,posx,tempres,vis);
maxsizhou=max(maxsizhou,tempres);
}
}
if (sum==0)
{
res=1;
vis[row][col]=1;
}
else
{
res=maxsizhou+1;
vis[row][col]=res;
}
return ;
}
};