NYOJ10,skiing

skiing

时间限制:3000 ms  |  内存限制:65535 KB
难度:5
描写叙述
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更长。其实,这是最长的一条。

输入
第一行表示有几组測试数据。输入的第二行表示区域的行数R和列数C(1 <= R,C <= 100)。以下是R行,每行有C个整数。代表高度h,0<=h<=10000。
后面是下一组数据。
输出
输出最长区域的长度。
例子输入
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
例子输出
25
来源
经典题目


import java.util.Arrays;
import java.util.Scanner;


public class NYOJ10_ieayoio {
	public static int [][]map;
	public static int [][]f;
	public static int []dx={0,1,0,-1,0};
	public static int []dy={0,0,-1,0,1};
	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		int t=input.nextInt();
		while (t-->0){
			int n=input.nextInt();
			int m=input.nextInt();
			map=new int [n+5][m+5];
			for (int i=0;i<map[0].length;i++)
				Arrays.fill(map[i], Integer.MAX_VALUE);
			f= new int [n+5][m+5];
			for (int i=0;i<f[0].length;i++)
				Arrays.fill(f[i], 1);
			for (int i=1;i<=n;i++)
				for (int j=1;j<=m;j++)
					map[i][j]=input.nextInt();
			for (int i=1;i<=n;i++)
				for (int j=1;j<=m;j++){
					dfs(i,j);
				}
			int max=Integer.MIN_VALUE;
			for (int i=1;i<=n;i++)
				for (int j=1;j<=m;j++)
				{
					if (max<f[i][j]) max=f[i][j];
				}
			System.out.println(max);
			
		}
	}
	static int dfs(int x,int y)
	{
		if (f[x][y]!=1) return f[x][y];
		if (isnoway(x,y)==false){
			return 1;
		}
		for (int i=1;i<=4;i++){
			int xx=x+dx[i];
			int yy=y+dy[i];
			if (map[x][y]>map[xx][yy]){
				int comway=1+dfs(xx,yy);
				if (f[x][y]<comway) f[x][y]=comway;
			}
		}
		return f[x][y];
	}
	static boolean isnoway(int x,int y){
		boolean flag=false;
		if (map[x][y]>map[x+dx[1]][y+dy[1]]) flag=true;
		if (map[x][y]>map[x+dx[2]][y+dy[2]]) flag=true;
		if (map[x][y]>map[x+dx[3]][y+dy[3]]) flag=true;
		if (map[x][y]>map[x+dx[4]][y+dy[4]]) flag=true;
		return flag;
	}

}


挺高兴的一直感觉没把握做的题,做了两天。经过调试通过例子后,没想到一次性提交就过了


方法就是深搜,只是就是加了一个数组f[x][y],来保存点(x,y)可滑到最低点的最长距离,dfs(x,y)用来深搜这个距离,若f[x][y]已存在,则将函数的值直接返回为f[x][y],

isnoway函数式来推断点(x,y)能否够向更低点滑行







原文地址:https://www.cnblogs.com/liguangsunls/p/6853938.html