• Dungeon Game 分类: Leetcode 2015-01-15 09:10 69人阅读 评论(0) 收藏


    The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

    The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

    Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).

    In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.


    Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.

    For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.

    -2 (K) -3 3
    -5 -10 1
    10 30 -5 (P)

    Notes:

    • The knight's health has no upper bound.

    • Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.

    这种类型的题目属于迷宫遍历,最容易想到就是动态规划或者深度搜索,这道题目用的是动态规划。动态规划问题实际上是求解一个初始值和递归关系。
    class Solution {
    public:
        int calculateMinimumHP(vector<vector<int> > &dungeon) {
            int m,n,i,j;
            m = dungeon.size();
            n = dungeon[0].size();
            int f[m][n];
            f[m-1][n-1] = max(0-dungeon[m-1][n-1],0); 
            for(i=m-2;i>=0;i--)
            {
                f[i][n-1]= max(-dungeon[i][n-1]+f[i+1][n-1],0);
            }
            for(j=n-2;j>=0;j--)
            {
                f[m-1][j]=max(-dungeon[m-1][j]+f[m-1][j+1],0);
            }
            for(i=m-2;i>=0;i--)
            {
                for(j=n-2;j>=0;j--)
                {
                    f[i][j]= max(min(f[i+1][j]-dungeon[i][j],f[i][j+1]-dungeon[i][j]),0);
                    
                }
            }
            return f[0][0]+1;
        }
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    上有传参下传json的接口调用
    通过群号,获取到群成员信息,下载头像到指定文件夹
    django模型 之 Meta
    k8s 日志的收集
    systemctl 管理服务
    安装JumpServer
    1 nginx的配置详解
    十六 RBAC
    python3 与linux间的小知识
    解决问题:OSError: mysql_config not found
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656975.html
Copyright © 2020-2023  润新知