题目:
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。当然25-24-23-…-3-2-1更长。事实上,这是最长的一条。
Input
输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,每行有C个整数,代表高度h,0<=h<=10000。
Output
输出最长区域的长度。
Sample Input
5 5
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
Sample Output
25
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define MAX 105
int m,n,maxn = -1;
int a[MAX][MAX],len[MAX][MAX];
int direction[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int bfs(int x,int y)
{
int ms = 0,tx,ty,s;
if(len[x][y] != 0) return len[x][y];
for(int i = 0;i < 4;i++){
tx = x + direction[i][0];
ty = y + direction[i][1];
if(tx < 0 || tx > (m - 1) || ty < 0 || ty > (n - 1)) continue;
if(a[tx][ty] < a[x][y]){
s = bfs(tx,ty);
ms = max(ms,s);
}
}
len[x][y] = ms + 1;
return len[x][y];
}
int main()
{
cin >> m >> n;
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++)
cin >> a[i][j];
}
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
maxn = max(maxn, bfs(i,j));
}
}
cout << maxn << endl;
return 0;
}
这道题时dp+bfs,对每一座山都进行bfs,计算出从这个滑坡走到最低点最大的步数,随后再选出所有滑坡的最大步数。
这路在进行bfs时可以保存某些之前滑坡到达最低点最大的步数,因为之后从别的滑坡再次经过这个滑坡就不用再递归了。