Leetcode 174. Dungeon Game (Hard) (cpp)

来源:互联网 发布:图书软件哪个好 编辑:程序博客网 时间:2024/05/17 06:43

Leetcode 174. Dungeon Game (Hard) (cpp)

Tag: Binary Search, Dynamic Programming

Difficulty: Hard


/*174. Dungeon Game (Hard)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.*/class Solution {public:    int calculateMinimumHP(vector<vector<int>>& dungeon) {        vector<int> t(dungeon[0].size(), 0);        for (int i = dungeon.size() - 1; i >= 0; i--) {            for (int j = dungeon[0].size() - 1; j >= 0; j--) {                if (i == dungeon.size() - 1 && j == dungeon[0].size() - 1) {                    t[j] = update(dungeon[i][j], 1);                } else if (i == dungeon.size() - 1) {                    t[j] = update(dungeon[i][j], t[j + 1]);                } else if (j == dungeon[0].size() - 1) {                    t[j] = update(dungeon[i][j], t[j]);                } else {                    t[j] = min(update(dungeon[i][j], t[j + 1]), update(dungeon[i][j], t[j]));                }            }        }        return t[0];    }private:    int update(int cur, int pre) {        if (cur < 0) {            return -cur + pre;        } else if (cur >= pre) {            return 1;        } else {            return pre - cur;        }        return 0;    }};


0 0
原创粉丝点击