滑雪(dfs)

https://www.luogu.org/problemnew/show/P1434

题目描述

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更长。事实上,这是最长的一条。

输入输出格式

输入格式:

 

输入的第一行为表示区域的二维数组的行数R和列数C(1≤R,C≤100)。下面是R行,每行有C个数,代表高度(两个数字之间用1个空格间隔)。

 

输出格式:

 

输出区域中最长滑坡的长度。

 

输入输出样例

输入样例#1: 复制

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

输出样例#1: 复制

25
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
#define N 120
int a[N][N],book[N][N],d[N][N],ans=1,r,c;
int next[4][2]={1,0,-1,0,0,1,0,-1};
int dfs(int i,int j)
{
	int tx,ty,k,t;
	t=d[i][j];
	for(k=0; k<4; k++)
	{                                          
		tx=i+next[k][0];
		ty=j+next[k][1];
		if(tx<=0 || ty<=0 || tx>r || ty>c || book[tx][ty] == 1 || a[tx][ty] >= a[i][j])
			continue;
		if(d[tx][ty]!=1)
			d[i][j]=max(t+d[tx][ty],d[i][j]);	
		else
		{
			book[tx][ty]=1;
			d[tx][ty]=dfs(tx,ty);
			book[tx][ty]=0;
			d[i][j]=max(t+d[tx][ty],d[i][j]);
		}
	}
	return d[i][j];
}
int main()
{
	int i,j;
	scanf("%d%d",&r,&c);
	for(i=1; i<=r; i++)
		for(j=1;j<=c;j++)
			scanf("%d",&a[i][j]);
	for(i=1; i<=r; i++)
		for(j=1; j<=c; j++)
			d[i][j]=1;
	for(i=1; i<=r; i++)
		for(j=1; j<=c; j++)
		{
			if(d[i][j]==1)
			{
				memset(book,0,sizeof(book));
				book[i][j]=1;
				dfs(i,j);
			}
			ans=max(ans,d[i][j]);
		}		
	printf("%d\n",ans);
	return 0;	
}

 

posted @ 2019-02-01 13:47  宿星  阅读(112)  评论(0编辑  收藏  举报