leetcode -- 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
.
-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.
解答:
一开始想到的做法是采用search DFS解,给定起点和终点,可以搜索所有从起点到终点的路径,然后贪心保存最小的路径之和
每次扩展分支的时候需保证体力值>0,这种做法时间复杂度太高,不能过large data set。
1 /* 2 * using dfs to find the minimum hp to go through the dungeon 3 */ 4 void get_through_dungeon(const vector<vector<int>> dungeon, int x, int y, 5 int row, int col, int& m_hp, int cur_m_hp, int cur_hp) { 6 if (x >= row || y >= col) { 7 return; 8 } 9 // find the princess 10 int dungeon_hp = dungeon[x][y]; 11 if (x == row - 1 && y == col - 1) { 12 if (dungeon_hp >= 0 && m_hp > cur_m_hp) { 13 m_hp = cur_m_hp; 14 } 15 else if (dungeon_hp < 0) { 16 if (abs(dungeon_hp) >= cur_hp) { 17 cur_m_hp += abs(dungeon_hp + cur_hp) + 1; 18 } 19 if (m_hp > cur_m_hp) { 20 m_hp = cur_m_hp; 21 } 22 } 23 return; 24 } 25 26 if (dungeon_hp < 0) { 27 if (abs(dungeon_hp) >= cur_hp) { 28 cur_m_hp += abs(dungeon_hp + cur_hp) + 1; 29 cur_hp = 1; 30 } 31 else { 32 cur_hp = cur_hp + dungeon_hp; 33 } 34 } 35 else { 36 cur_hp += dungeon_hp; 37 } 38 39 get_through_dungeon(dungeon, x + 1, y, row, col, m_hp, cur_m_hp, cur_hp); 40 get_through_dungeon(dungeon, x, y + 1, row, col, m_hp, cur_m_hp, cur_hp); 41 } 42 43 int calculateMinimumHP(vector<vector<int>> &dungeon) { 44 int row = dungeon.size(); 45 if (row == 0) { 46 return 0; 47 } 48 int col = dungeon[0].size(); 49 int m_hp = INT_MAX; 50 get_through_dungeon(dungeon, 0, 0, row, col, m_hp, 1, 1); 51 52 return m_hp; 53 }