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-11(从 24 开始,在 11 结束)。当然 25-24-23-…-33-22-11 更长。事实上,这是最长的一条。
输入格式
输入的第一行为表示区域的二维数组的行数 R 和列数 C。下面是 R 行,每行有 C个数,代表高度(两个数字之间用 11 个空格间隔)。
输出格式
输出区域中最长滑坡的长度。
题解(记忆搜索)
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
static int R = scan.nextInt(),C = scan.nextInt();
static int [][]numb = new int[R][C];
static int [][]cpnumb = new int[R][C];
public static void main(String[] args) {
for(int i=0;i<R;i++) {
for(int j=0;j<C;j++) {
numb[i][j] = scan.nextInt();
}
}
int ans =1;
scan.close();
for(int i=0;i<R;i++) {
Arrays.fill(cpnumb[i], 1);
}
for(int i=0;i<R;i++) {
for(int j=0;j<C;j++) {
ans=Math.max(ans,dfs(i,j));
}
}
System.out.println(ans);
}
static int dfs(int x,int y) {
if(cpnumb[x][y]!=1)return cpnumb[x][y];//记忆化深度优先搜索
int []dx = {1,-1,0,0};
int []dy = {0,0,-1,1};
for(int i=0;i<4;i++){
int xx=dx[i]+x;
int yy=dy[i]+y;//四个方向
if(xx>=0&&yy>=0&&xx<R&&yy<C&&numb[x][y]>numb[xx][yy]){
dfs(xx,yy);
cpnumb[x][y]=Math.max(cpnumb[x][y],cpnumb[xx][yy]+1);
}
}
return cpnumb[x][y];
}
}