Language:
滑雪
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 Source |
import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner;
public class Main {//1088 Accepted 5328K 1547MS Java 1388B
private static int j,M,i,N,temp;
private static int[][] a;
private static int[][] vis;//未赋值时都为0
private static int f(int i, int j) {
int sum=0;
if(i<1 || i>N || j<1 || j>M){//超界后,自动返回
return 0;
}
if(vis[i][j]!=0){//出现过
return vis[i][j];
}
if(a[i][j]>a[i-1][j]){//向下查找
temp=f(i-1,j);
if(sum<temp)
sum=temp;
}
if(a[i][j]>a[i][j-1]){//左
temp=f(i,j-1);
if(sum<temp)
sum=temp;
}
if(a[i][j]>a[i][j+1]){//右
temp=f(i,j+1);
if(sum<temp)
sum=temp;
}
if(a[i][j]>a[i+1][j]){//上
temp=f(i+1,j);
if(sum<temp)
sum=temp;
}
return vis[i][j]=sum+1;//递归到一个数组元素查找最长轨迹结束才返回最终的值!
}
public static void main(String[] args) {
Scanner scan=new Scanner(new BufferedInputStream(System.in));
while(scan.hasNext()){
N=scan.nextInt();
M=scan.nextInt();
a =new int [N+2][M+2];
vis = new int [N+2][M+2];//每次都需初始化!!!
int max = 0;
temp=0;
for(i = 1 ;i <= N; i++){
for(j = 1; j <= M; j++){
a[i][j] =scan.nextInt();
}
}
for(i=1;i<=N;i++){
for(j=1;j<=M;j++){
temp = f(i,j);//返回对每一个数组元素进行搜索最大路经后的返回值
if(max<temp)//与以前保留的值进行对比,取最大的。
max=temp;
}
}
System.out.println(max);
}
}
}