对应POJ题目:点击打开链接
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 80180 | Accepted: 29857 |
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
思路:枚举搜索每个点,直接搜会超时,当找到一个的最大长度,用mark[i][j] 记录下来,下次再遇到这个点,就直接取数!
#include<cstdio> #include<cstdlib> #include <stdio.h> #include <stdlib.h> #include <string.h> #define M 100 int G[M][M]; int vis[M][M]; int mark[M][M]; int r, c; void Dfs(int i, int j, int &step, int &max_step) { if(vis[i][j] || i < 0 || i == r || j < 0 || j == c) return; if(mark[i][j]){ /* 如果走到了当前位置,则不需要再往下递归,因为此值已记录过,直接加上就行了 */ step += mark[i][j]; if(step > max_step) max_step = step; step -= mark[i][j]; vis[i][j] = 0; return; } vis[i][j] = 1; int base = G[i][j]; step++; if(G[i+1][j] < base) Dfs(i + 1, j, step, max_step); if(G[i-1][j] < base) Dfs(i - 1, j, step, max_step); if(G[i][j+1] < base) Dfs(i, j + 1, step, max_step); if(G[i][j-1] < base) Dfs(i, j - 1, step, max_step); if(step > max_step) max_step = step; step--; vis[i][j] = 0; return; } int main() { //freopen("in.txt","r",stdin); while(~scanf("%d%d", &r, &c)) { memset(mark, 0, sizeof(mark)); int i, j; for(i=0; i<r; i++) for(j=0; j<c; j++) scanf("%d", &G[i][j]); int max_step = 0; int step = 0; for(i=0; i<r; i++){ for(j=0; j<c; j++){ memset(vis, 0, sizeof(vis)); int m = 0; Dfs(i, j, step, m); mark[i][j] = m; /* 记录从点G[i,j]开始的最长距离 */ if(m > max_step) max_step = m; } } printf("%d\n", max_step); } return 0; }