百练 滑雪(dp+dfs)

转自:https://blog.csdn.net/chang_mu/article/details/38066187

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

#include <stdio.h>  
#define maxn 102  
  
int dp[maxn][maxn], map[maxn][maxn];  
int n, m, mov[][2] = {-1, 0, 1, 0, 0, 1, 0, -1};  
  
bool check(int i, int j)  
{  
    return i >= 0 && i < n && j >= 0 && j < m;  
}  
  
int DFS(int x, int y)  
{  
    if(dp[x][y]) return dp[x][y];  
    int i, j, k, t, ans = 1;  
    for(k = 0; k < 4; ++k){  
        i = x; j = y;  
        i += mov[k][0]; j += mov[k][1];  
        if(check(i, j) && map[i][j] < map[x][y]){  
            t = 1 + DFS(i, j);  
            if(t > ans) ans = t;  
        }  
    }  
    return dp[x][y] = ans; //important! better than return ans;  
}  
  
int main()  
{  
    int i, j, ans;  
    scanf("%d%d", &n, &m);  
    for(i = 0; i < n; ++i){  
        for(j = 0; j < m; ++j) scanf("%d", &map[i][j]);  
    }  
    ans = 1;  
    for(i = 0; i < n; ++i){  
        for(j = 0; j < m; ++j){  
            dp[i][j] = DFS(i, j);  
            if(ans < dp[i][j]) ans = dp[i][j];  
        }  
    }  
    printf("%d\n", ans);  
    return 0;  
}  

PS:使用动态规划,对每一个元素,进行四个方向的判断,dp[x][y]=max{dp[i][j]+1,dp[x][y]},dp[i][j]表示点xy中四个方向的滑梯个数。厉害。DFS中,如果是已经计算过了,那么就直接返回dp[x][y],使用递归。

对这种矩阵中上下左右方向的三步:①定义方向数组dir[][2];②对x,y进行循环操作;③操作之后进行check,是否越界,如果未越界那么就接着操作。

猜你喜欢

转载自blog.csdn.net/huanting74/article/details/80378316