做法:dfs记忆化搜索
思路:
用函数找到每个点能滑行的最大值,再遍历每个点能滑行的最大值 找到答案输出
dfs函数展示:
int dfs(int x, int y)
{
if (res[x][y])
return res[x][y]; // 记忆化搜索
res[x][y] = 1; // 如果该点没有值,赋初值为1
for (int i = 0; i < 4; i++)
{
int tx = dx[i] + x;
int ty = dy[i] + y;
if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && arr[tx][ty] > arr[x][y]) // 能够移动的条件
{
dfs(tx, ty); // 能移动就继续移动,深搜
res[x][y] = max(res[x][y], res[tx][ty] + 1); // 该点的值取 该点 与 下一点滑行的最大距离+1 的最大值
}
}
return res[x][y]; // 返回答案//或者在递归的时候返回值
}
自己写的时候发现的问题:
我疑惑函数中
if (res[x][y])
return res[x][y];
能否确保返回的res[x][y]一定是最大值?
实际上每次遍历到该点的时候也对该点实现了向四个方向深搜,找到了该点的最大值。其实dfs函数实现的功能就是找点(x,y)的最大值,并给res[x][y]赋上该最大值。
AC代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int arr[N][N]; // 存数据
int res[N][N]; // 存从每个点出发,最多能滑行的长度
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1}; // 方向
int ans = 0;
int n, m; // n是行,m是列
int dfs(int x, int y)
{
if (res[x][y])
return res[x][y]; // 记忆化搜索
res[x][y] = 1; // 如果该点没有值,赋初值为1
for (int i = 0; i < 4; i++)
{
int tx = dx[i] + x;
int ty = dy[i] + y;
if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && arr[tx][ty] > arr[x][y]) // 能够移动的条件
{
dfs(tx, ty); // 能移动就继续移动,深搜
res[x][y] = max(res[x][y], res[tx][ty] + 1); // 该点的值取 该点 与 下一点滑行的最大距离+1 的最大值
}
}
return res[x][y]; // 返回答案//或者在递归的时候返回值
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> arr[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
ans = max(ans, dfs(i, j)); // 取最大值
}
cout << ans << endl;
return 0;
}