329. 矩阵中的最长递增路径
DP
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix)
{
if(matrix.size()==0 or matrix[0].size()==0)
{
return 0;
}
int m=matrix.size(),n=matrix[0].size();
vector<vector<int>> dp(m,vector<int>(n,-1)); //dp[i][j]表示(i,j)节点开始(包含自身)的最长递增路径长度
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j)
{
dfs(matrix,dp,i,j,m,n);
}
}
int res=1;
for(auto& row:dp)
{
for(int col:row)
{
res=max(res,col);
// cout<<col<<" ";
}
cout<<endl;
}
return res;
}
int dfs(vector<vector<int>>& matrix,vector<vector<int>>& dp,int i,int j,int m,int n)
{
if(dp[i][j]!=-1)
{
return dp[i][j];
}
dp[i][j]=1;
if(i+1<m and matrix[i+1][j]>matrix[i][j])
{
dp[i][j]=max(dp[i][j],1+dfs(matrix,dp,i+1,j,m,n));
}
if(i-1>=0 and matrix[i-1][j]>matrix[i][j])
{
dp[i][j]=max(dp[i][j],1+dfs(matrix,dp,i-1,j,m,n));
}
if(j+1<n and matrix[i][j+1]>matrix[i][j])
{
dp[i][j]=max(dp[i][j],1+dfs(matrix,dp,i,j+1,m,n));
}
if(j-1>=0 and matrix[i][j-1]>matrix[i][j])
{
dp[i][j]=max(dp[i][j],1+dfs(matrix,dp,i,j-1,m,n));
}
return dp[i][j];
}
};
进击的小🐴农