您的位置:首页 > 其它

POJ1088滑雪

2016-01-13 12:14 197 查看
Description

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更长。事实上,这是最长的一条。
Input

输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,每行有C个整数,代表高度h,0<=h<=10000。
Output

输出最长区域的长度。
Sample Input

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
Sample Output

25
Source

SHTSC 2002


链接: http://poj.org/problem?id=1088

这是POJ经典的记忆化搜索结构题目,很早以前就知道这道题目,今天偶然想起来又看了一眼Discuss,决定将大牛的方法记录下来。 这道题目的意思是,给定一个二维矩阵里,找到一条最长的下降坡道(4-connected,从最大值到最小值为递减的一条path)。

我们主要可以维护一个count[][]矩阵,对上下左右分别用dfs来记录下每个位置的最大count。之后也要做一些pruning,比如当count[i][j] > 0的时候,表示这个位置已经被计算过,可以直接返回count[i][j]来省略重复计算。

import java.util.*;

public class Solution {
private int[][] count;

public int findDownHillSki(int[][] board) {
count = new int[board.length][board[0].length];        // matrix count for counting
int max = 0;
for (int i = 0; i < board.length; i++) {            // fill count[][] using findMax(i, j, board)
for (int j = 0; j < board[0].length; j++) {
findMax(i, j, board);
max = Math.max(max, count[i][j]);
}
}
return max;
}

private int findMax(int i, int j, int[][] board) {
int max = 0;
if (count[i][j] > 0) {
return count[i][j];
}

if (i - 1 >= 0) {
if (board[i][j] > board[i - 1][j]) {
max = Math.max(max, findMax(i - 1, j, board));
}
}
if (j - 1 >= 0) {
if (board[i][j] > board[i][j - 1]) {
max = Math.max(max, findMax(i, j - 1, board));
}
}
if (i + 1 < count.length) {
if (board[i][j] > board[i + 1][j]) {
max = Math.max(max, findMax(i + 1, j, board));
}
}
if (j + 1 < count[0].length) {
if (board[i][j] > board[i][j + 1]) {
max = Math.max(max, findMax(i, j + 1, board));
}
}
return count[i][j] = max + 1;
}
}


测试:

public class Program {

public static void main(String[] args) {

int[][] board = {{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}};

int[][] board1 = {{1, 2, 3, 4, 5},
{6, 5, 4, 3, 2}};

Solution sol = new Solution();
int res = sol.findDownHillSki(board);
System.out.println(res);
}
}


Reference:
http://poj.org/showmessage?message_id=113914
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: