标签:
Description
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Input
Output
Sample Input
5 5 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
Sample Output
25
代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 6 int R,C; 7 long dp[105][105]; 8 int a[105][105]; 9 10 long dfs(int i,int j) 11 { 12 //为防止下标+1或-1时数组越界,故dp数组从1开始存放数据 13 if(dp[i+1][j+1]!=0) 14 return dp[i+1][j+1]; 15 16 dp[i+1][j+1] = 1; 17 18 if(a[i-1][j]<a[i][j]&&i!=0) //向上 19 dp[i+1][j+1] = max(dp[i+1][j+1],dfs(i-1,j)+1); 20 if(a[i][j+1]<a[i][j]&&j!=C-1) //向右 21 dp[i+1][j+1] = max(dp[i+1][j+1],dfs(i,j+1)+1); 22 if(a[i+1][j]<a[i][j]&&i!=R-1) //向下 23 dp[i+1][j+1] = max(dp[i+1][j+1],dfs(i+1,j)+1); 24 if(a[i][j-1]<a[i][j]&&j!=0) //向左 25 dp[i+1][j+1] = max(dp[i+1][j+1],dfs(i,j-1)+1); 26 27 return dp[i+1][j+1]; 28 } 29 30 int main() 31 { 32 while(cin>>R>>C) 33 { 34 for(int i = 0; i < R; i++) 35 for(int j = 0; j < C; j++) 36 { 37 cin>>a[i][j]; 38 } 39 memset(dp,sizeof(dp),0); 40 int ans = -1; 41 for(int i = 0; i < R; i++) 42 for(int j = 0; j < C; j++) 43 { 44 dfs(i,j); //逐个搜索一遍,相当于在dfs中记忆化搜索 45 } 46 47 //从dp数组中找最大的就是答案 48 for(int i = 1; i <= R; i++) 49 for(int j = 1; j <= C; j++) 50 { 51 if(dp[i][j]>ans) 52 ans=dp[i][j]; 53 } 54 55 cout<<ans<<endl; 56 } 57 return 0; 58 }
标签:
原文地址:http://www.cnblogs.com/cjshuang/p/4655223.html