Description
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
问题分析
假设已经实现函数:int find(int x,int y)返回从点(x,y)的最长坡道的长度,那么我们只需要遍历题目给出的数组,计算长度取最大值即为最终答案。
函数实现:
我们利用temp[i][j]数组判断是否已经计算过当前点(i,j)避免重复计算,这样能够节省时间。如果已经计算过当前节点直接返回temp[i][j]中存储的值。
接着调用find函数计算上下左右四个节点中满足条件的节点,并取最大值max。
返回max加1。
代码实现
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int array[101][101];
int temp[101][101];
int find(int x,int y,int R,int C){
int maxi=0;
if(temp[x][y]!=1)return temp[x][y];
if(y-1>=0&&array[x][y]>array[x][y-1])maxi=max(maxi,temp[x][y-1]=find(x,y-1,R,C));
if(x-1>=0&&array[x][y]>array[x-1][y])maxi=max(maxi,temp[x-1][y]=find(x-1,y,R,C));
if(y+1<C&&array[x][y]>array[x][y+1])maxi=max(maxi,temp[x][y+1]=find(x,y+1,R,C));
if(x+1<R&&array[x][y]>array[x+1][y])maxi=max(maxi,temp[x+1][y]=find(x+1,y,R,C));
return maxi+1;
}
int main(){
int R,C;
while(scanf("%d %d",&R,&C)==2){
for(int i=0;i<R;i++)
for(int j=0;j<C;j++){
scanf("%d",&array[i][j]);
temp[i][j]=1;
}
int maxi=0;
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
maxi=max(maxi,find(i,j,R,C));
printf("%d\n",maxi);
}
return 0;
}