题意:给一个图,每个位置可以走上下左右四个方向,且必须所走下一节点值小于当前值,求最长路长度
思路:求最长路肯定是dfs,直接dfs超时,就用记忆化搜索,将搜到的结果放到dp里,搜索完后dp[i][j]即节点i, j的最长路长度
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n, m, g[105][105], dp[105][105];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
void dfs(int x, int y)
{
if (dp[x][y])
return;
dp[x][y] = 1;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && g[nx][ny] < g[x][y]) {
dfs(nx, ny);
dp[x][y] = max(dp[x][y], dp[nx][ny]+1);
}
}
}
int main()
{
while (cin >> n >> m) {
memset(dp, 0, sizeof(dp));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> g[i][j];
int h = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
dfs(i, j);
h = max(h, dp[i][j]);
}
cout << h << endl;
}
return 0;
}