dp[i][j]表示从i,j开始的最长路径,记忆化搜索一下。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define maxn 120 int dp[maxn][maxn],map[maxn][maxn]; int r,c; int dfs(int i,int j) { if(dp[i][j]!=-1) return dp[i][j]; else { int ans=1; if(j+1<=c&&map[i][j]>map[i][j+1]) ans=max(ans,dfs(i,j+1)+1); if(j-1>=1&&map[i][j]>map[i][j-1]) ans=max(ans,dfs(i,j-1)+1); if(i+1<=r&&map[i][j]>map[i+1][j]) ans=max(ans,dfs(i+1,j)+1); if(i-1>=1&&map[i][j]>map[i-1][j]) ans=max(ans,dfs(i-1,j)+1); dp[i][j]=ans; return ans; } } int main() { int i,j; while(scanf("%d%d",&r,&c)!=EOF) { for(i=1;i<=r;i++) for(j=1;j<=c;j++) scanf("%d",&map[i][j]); memset(dp,-1,sizeof(dp)); int Max=-1; for(i=1;i<=r;i++) for(j=1;j<=c;j++) { if(dp[i][j]==-1) dp[i][j]=dfs(i,j); Max=max(dp[i][j],Max); } printf("%d ",Max); } return 0; }