题目:
![](https://i-blog.csdnimg.cn/blog_migrate/79da1715348ffea5b38ae6e7e80da89f.png)
思路:
dfs直接写的话时间会超限
这里用到了记忆化搜索,记住每个格子搜索的最大值,下次搜索搜到已经记忆的格子可以直接+这个格子的最大值
代码:
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
int r,c;
int mx;
//int nx;在此处定义会出错,不能定义为全局变量
int a[4] = {1,-1,0,0};
int b[4] = {0,0,-1,1};
int dp[110][110];
int rem[110][110];
int dfs(int x, int y) {
if (rem[x][y])
return rem[x][y];
rem[x][y] = 1;
for (int i = 0; i < 4; i++) {
int nx = x + a[i];
int ny = y + b[i];//在此处定义不会出错
if (nx > 0 && nx <= r && ny > 0 && ny <= c && dp[nx][ny] < dp[x][y]) {
dfs(nx, ny);
rem[x][y] = max(rem[x][y], rem[nx][ny] + 1);
}
}
return rem[x][y];
}
int main() {
cin >> r>>c;
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
cin >> dp[i][j];
}
}
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
mx = max(mx, dfs(i,j));
}
}
cout <<mx;
}