您的位置:首页 > 其它

poj1088

2016-01-04 22:17 281 查看
poj1088

题意:给出一个矩阵,求出一个点上下左右走按递减的最大长度。

分析:思想差不多算是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;

}
}

}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 递归算法 dfs dp