leetcode:Dungeon Game

来源:互联网 发布:湖南卫视网络在线直播 编辑:程序博客网 时间:2024/05/22 14:52

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)-33-5-1011030-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.

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

Subscribe to see which companies asked this question



class Solution {public:    int calculateMinimumHP(vector<vector<int>>& dungeon) {                vector<vector<int>> auxVtr(dungeon.size(), vector<int>(dungeon[0].size()));                int m = dungeon.size();        int n = dungeon[0].size();                // auxVtr[i][j] 表示在没有对 dungeon[i][j]进行操作前的最小值,这个最小值要大于等于1        // 如果dungeon[m-1][n-1] 为正数 (1), 那么auxVtr[m-1][n-1]最小也要为1        // 如果dungeon[m-1][n-1] 为负数 (-3)那么auxVtr[m-1][n-1]最小要为4        auxVtr[m-1][n-1] = dungeon[m-1][n-1] > 0? 1 : 1-dungeon[m-1][n-1];                        for (int j=n-2; j>=0; j--)        {            // 若auxVtr[m-1][n-1]为3, dungeon[m-1][n-2] 为1,则auxVtr[m-1][n-2]要为2            // 若auxVtr[m-1][n-1]为3, dungeon[m-1][n-2] 为4, 尽管 3-4=-1也能使auxVtr[m-1][n-1]OK,但是不能保证则auxVtr[m-1][n-2] > 1,所以这时候则auxVtr[m-1][n-2] 只能为1            auxVtr[m-1][j] = max(1, auxVtr[m-1][j+1]-dungeon[m-1][j]);        }                for (int i=m-2; i>=0; i--)        {            auxVtr[i][n-1] = max(1, auxVtr[i+1][n-1]-dungeon[i][n-1]);        }                for (int i=m-2; i>=0; i--)        {            for (int j=n-2; j>=0; j--)            {                int right = max(1, auxVtr[i][j+1] - dungeon[i][j]);//这个max表达式一定要注意                int down  = max(1, auxVtr[i+1][j] - dungeon[i][j]);                                auxVtr[i][j] = min(right, down);            }        }                return auxVtr[0][0];    }};


0 0
原创粉丝点击