题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=10
我的第一种方法是对矩阵的每个顶点当作起点搜索一遍,结果是用时260MS,
代码:
#include <cstdio> #include <cstring> using namespace std; #define inf 1e6 int mp[105][105]; int r,c; int v[105][105]; int dx[] = {-1,0,1,0}; int dy[] = {0,1,0,-1}; int ans; void dfs(int x,int y,int step) { if(step > ans) { ans = step; } for(int i = 0; i < 4; ++i) { int tx = x + dx[i]; int ty = y + dy[i]; if(tx >= 1&&tx <= r&&ty>=1&&ty<=c&&mp[tx][ty] > mp[x][y] && !v[tx][ty]) { v[tx][ty] = 1; dfs(tx,ty,step + 1); v[tx][ty] = 0; } } } int main() { int _; scanf("%d",&_); while(_--) { scanf("%d%d",&r,&c); for(int i = 1; i <= r; ++i) for(int j = 1; j <= c; ++j) scanf("%d",&mp[i][j]); ans = -inf; for(int i = 1; i <= r; ++i) for(int j = 1; j <= c; ++j) { memset(v,0,sizeof v); dfs(i,j,1); } printf("%d\n",ans); } return 0; }
#include<stdio.h> #include<memory.h> int R, C; int a[101][101]; int f[101][101]; inline int max(int a, int b) { return a>b?a:b; } inline int max(int a, int b, int c, int d) { return max(max(a, b), max(c, d)); } int dfs(int row, int col, int h) { if(row < 1 || row > R || col < 1 || col > R || h <= a[row][col]) return 0; if(f[row][col] >= 0) return f[row][col]; f[row][col] = max(dfs(row - 1, col, a[row][col]), dfs(row, col + 1, a[row][col]), dfs(row + 1, col, a[row][col]), dfs(row, col - 1, a[row][col])) + 1; //动规,当前最大滑雪长度为四周比该点低的最大滑雪长度加1 return f[row][col]; } int main() { int T, i, j; scanf("%d", &T); while(T--) { int max = 0; memset(f, -1, sizeof(f)); scanf("%d%d", &R, &C); for(i = 1; i <= R; ++i) { for(j = 1; j <= R; ++j) { scanf("%d", &a[i][j]); } } for(i = 1; i <= R; ++i) { for(j = 1; j <= R; ++j) { int num = dfs(i, j, 0xffffff); if(max < num) max = num; } } printf("%d\n", max); } return 0; }