题意:给出一个矩阵,求出一个点上下左右走按递减的最大长度。
分析:思想差不多算是dfs,递归一块,如果要列可以列出dp方程,也算dp。大体的跟dfs递归算法一样,每个点有且仅有一次能被操作到,这可以用color[][]数组来解决。一旦找到上下左右比他小的,进行递归,并且长度加一。最后返回一个上下左右最大的一个数。
AC java代码如下:
import java.util.Scanner;
public class poj1088 {
static int r;
static int c;
static int[][] color;
static int[][] arr;
static int len[][];
static int max = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
r = scan.nextInt();
c = scan.nextInt();
arr = new int[r][c];
color = new int[r][c];
len = new int[r][c];
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++) {
arr[i][j] = scan.nextInt();
color[i][j] = 0;
}
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++) {
if (color[i][j] == 0)
dfs(i, j);
if (len[i][j] > max)
max = len[i][j];
}
System.out.println(max);
}
private static int dfs(int i, int j) {
if (color[i][j] == 1)
return len[i][j];
else {
int temp = 1;
color[i][j] = 1;
if (i > 0 && arr[i][j] > arr[i - 1][j]) {
temp = dfs(i - 1, j) + 1;
}
if (j > 0 && arr[i][j] > arr[i][j - 1]) {
int temp1 = dfs(i, j - 1) + 1;
if (temp < temp1)
temp = temp1;
}
if (i < r - 1 && arr[i][j] > arr[i + 1][j]) {
int temp1 = dfs(i + 1, j) + 1;
if (temp < temp1)
temp = temp1;
}
if (j < c - 1 && arr[i][j] > arr[i][j + 1]) {
int temp1 = dfs(i, j + 1) + 1;
if (temp < temp1)
temp = temp1;
}
len[i][j] = temp;
return temp;
}
}
}