题目
Michael 喜欢滑雪。这并不奇怪,因为滑雪的确很刺激。可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你。Michael 想知道在一个区域中最长的滑坡。区域由一个二维数组给出。数组的每个数字代表点的高度。下面是一个例子:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度会减小。在上面的例子中,一条可行的滑坡为 24−17−16−1(从 24 开始,在 1 结束)。当然 25-24-23-……-3-2-1 更长。事实上,这是最长的一条。
Input
输入的第一行为表示区域的二维数组的行数 R 和列数 C。下面是 R 行,每行有 C 个数,代表高度(两个数字之间用 1 个空格间隔)。
Output
输出区域中最长滑坡的长度。
思路
因为数据较大,一般的搜索肯定会超时,因此,我们可以用记忆化搜索,在搜索的同时记录下当前值,避免重复搜索,降低时间复杂度
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<bitset>
#include<set>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS 1
#define ll long long
#define pub push_back
#define pob pop_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define inf 2e9
#define llf 1e19
#define endl "\n"
const ll mod = 1e9 + 7;
ll qpow(ll base, ll power)
{
ll res = 1;
while (power > 0)
{
if (power & 1) res = base * res % mod;
power >>= 1;
base = base * base % mod;
}
return res;
}
ll gcd(ll a, ll b)
{
return b == 0 ? a : gcd(b, a % b);
}
ll lcm(ll a, ll b)
{
return a / gcd(a, b) * b;
}
double dis(double x, double y, double x1, double y1)
{
return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
}
double dis1(double x, double y, double z, double x1, double y1, double z1)
{
return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1) + (z - z1) * (z - z1));
}
double chaji(double x1, double x2, double y1, double y2)
{
return x1 * y2 - x2 * y1;
}
int r, c, ans, a[110][110], cnt[110][110];
int dfs(int x, int y)
{
int way[4][2] = { 1,0,0,1,0,-1,-1,0 };
if (cnt[x][y]) return cnt[x][y];//记忆化搜索
cnt[x][y] = 1;
for (int i = 0; i < 4; i++)
{
int xx = x + way[i][0];
int yy = y + way[i][1];
if (xx >= 1 && xx <= r && yy >= 1 && yy <= c && a[x][y] > a[xx][yy])
{
dfs(xx, yy);
cnt[x][y] = max(cnt[x][y], cnt[xx][yy] + 1);//记录下当前值
}
}
return cnt[x][y];
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int i, j;
cin >> r >> c;
for (i = 1; i <= r; i++)
{
for (j = 1; j <= c; j++)
{
cin >> a[i][j];
}
}
for (i = 1; i <= r; i++)
{
for (j = 1; j <= c; j++)
{
ans = max(ans, dfs(i, j));
}
}
cout << ans;
}