题目描述
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 sc = new Scanner(System.in);
static int n = sc.nextInt();
static int m = sc.nextInt();
/**
* 矩阵数组
*/
static int[][] arr = new int[n][m];
/**
* 记录状态数组
*/
static int[][] state = new int[n][m];
/**
* 上下左右数组
*/
static int[] dx = {0, 0, 1, -1};
static int[] dy = {1, -1, 0, 0};
public static void main(String[] args) throws Exception {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt();
}
}
sc.close();
for (int i = 0; i < n; i++) {
//将状态方程的值全部赋为1,表示未走过
Arrays.fill(state[i], 1);
}
int res = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
//因为最大的点的路径不一定是最长的,所以需要将每个点进行一次遍历
res = Math.max(res,dfs(i,j));
}
}
System.out.println(res);
}
public static int dfs(int x, int y) {
if (state[x][y] != 1){
//表示该路径已经被走过,直接返回
return state[x][y];
}
for (int i = 0; i < 4; i++) {
//依次递归循环上下左右四个方向
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 0 && yy >= 0 && xx < n && yy < m && arr[x][y] > arr[xx][yy] ){
//如果不是边界且满足值比原来的小 进行递归
dfs(xx,yy);
//每次找最大的点,进行迭代,这样才能找到最长的路径
state[x][y] = Math.max(state[x][y],state[xx][yy] + 1);
}
}
return state[x][y];
}
}