LeetCode: 174. Dungeon Game

LeetCode: 174. Dungeon Game

题目描述

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.

Note:

  • 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.

解题思路 —— 动态规划

利用动态规划,反推从 (i, j) 坐标到 P 的位置所需最低初始血量。

AC 代码

class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
        vector<vector<int>> minHeathToHere(dungeon);

        for(int i = minHeathToHere.size()-1; i >= 0; --i)
        {
            for(int j = minHeathToHere[i].size()-1; j >= 0; --j)
            {
                int health = INT_MIN;
                if(i < minHeathToHere.size()-1)
                {
                    health = minHeathToHere[i][j] + minHeathToHere[i+1][j];
                }
                if(j < minHeathToHere[i].size()-1)
                {
                    health = max(minHeathToHere[i][j] + minHeathToHere[i][j+1], health);
                }
                if(health == INT_MIN) health = minHeathToHere[i][j];

                if(health > 0) health = 0;
                minHeathToHere[i][j] = health;
            }
        }

        return 1-minHeathToHere[0][0];
    }
};
全部评论

相关推荐

半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务