滑雪 【记忆化搜索】

滑雪

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

题意概括:

  每一个点只能向其上下左右四个方向中,比其高度低的点走,求最长连续能滑几次。

解题分析:

  这道题直接搜索每一个点的话会超时,用记忆化搜索,当搜完一个点后起值就是当前点所能达到的最大距离,如果比他高的点搜到他时,直接返回其值就可以了。

AC代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

#define N 110

int n, m;
int e[N][N], book[N][N];
int Next[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};

int dfs(int x, int y)
{
    if(book[x][y]) return book[x][y];//如果该点已经搜索过,说明其已经是当时最优值,直接返回其值就可以。
    for(int i = 0; i < 4; i++){
        int tx = x+Next[i][0];
        int ty = y+Next[i][1];
        if(e[tx][ty] >= e[x][y] || tx < 0 || tx >= n || ty < 0 || ty >= m) continue;
        int Max;
        Max = dfs(tx, ty);
        book[x][y] = max(book[x][y], Max);
    }
    book[x][y]++;//他自己也算一步
    return book[x][y];
}

int main()
{

    int i, j, k, Max, x, y;

    while(~scanf("%d%d", &n, &m)){
        Max = -9;
        memset(book, 0, sizeof(book));
        for(i = 0; i < n; i++){
            for(j = 0; j < m; j++)
                scanf("%d", &e[i][j]);
        }
        for(i = 0; i < n; i++){
            for(j = 0; j < m; j++){
                Max = max(dfs(i, j), Max);
            }
        }
        printf("%d\n", Max);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/k_young1997/article/details/80234739