题目链接原题地址
经典问题,该问题具有最有子结构性质和无后效性,可以用动态规划,也可以用记忆化搜索,代码如下:
#include <iostream> using namespace std; #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> int d[][2] = {0,1,1,0,0,-1,-1,0}; int f[110][110]; int map[110][110]; int n,m; int check(int x, int y) { if (x >=n || x < 0) return 0; if (y >=m || y < 0) return 0; return 1; } int find(int x, int y) { int maxl = 0; for (int i = 0; i < 4; ++i) { int xx = x + d[i][0]; int yy = y + d[i][1]; if (check(xx,yy)) { if (map[x][y] > map[xx][yy]) { maxl = max(maxl,f[xx][yy]==0?find(xx,yy):f[xx][yy]); } } } return f[x][y] = maxl + 1; } int main() { int T; cin >> T; while (T--) { cin >> n >> m; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> map[i][j]; } } memset(f,0,sizeof(f)); int ans = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (f[i][j] == 0) { ans = max(ans,find(i,j)); } } } cout << ans << endl; } return 0; }
时间: 2024-10-08 20:20:05