水题,记忆化搜索,队列bfs均可
我们定义f[i][j]为到(i, j)的最长路径。然后就不难得出状态转移方程,然后使用无脑dfs,或者有脑递推都是可以的。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 105;
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
struct node
{
int x, y;
};
int anss = 0;
int table[maxn][maxn];
int hi = 0;
int n, m;
queue<node> q;
int dp[maxn][maxn];
int dfs(int x, int y) {
int maxx = 0;
if(x == 0 || y == 0) return dp[x][y] = 0;
if(dp[x][y]) return dp[x][y];
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(table[nx][ny] > table[x][y]) maxx = max(maxx, dfs(nx, ny));
}
return dp[x][y] = maxx + 1;
}
int main() {
cin >> n >> m;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
cin >> table[i][j];
if(table[i][j] > hi) {
while(!q.empty()) q.pop();
q.push((node){i, j});
hi = table[i][j];
}
if(table[i][j] == hi) {
q.push((node){i, j});
}
}
}
while(!q.empty()) {
node fr = q.front(); q.pop();
dp[fr.x][fr.y] = 1;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
anss = max(anss, dfs(i, j));
}
}
}
cout << anss;
}