码迷,mamicode.com
首页 > 其他好文 > 详细

NYOJ10,skiing

时间:2014-07-22 23:57:48      阅读:750      评论:0      收藏:0      [点我收藏+]

标签:java   深搜   

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)是否可以向更低点滑行







NYOJ10,skiing

标签:java   深搜   

原文地址:http://blog.csdn.net/ieayoio/article/details/38050795

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!