|
| 1 | +## 174. Dungeon Game |
| 2 | + |
| 3 | +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. |
| 4 | + |
| 5 | +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. |
| 6 | + |
| 7 | +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). |
| 8 | + |
| 9 | +In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +Write a function to determine the knight's minimum initial health so that he is able to rescue the princess. |
| 14 | + |
| 15 | +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. |
| 16 | + |
| 17 | + |
| 18 | +https://leetcode.com/problems/dungeon-game/ |
| 19 | + |
| 20 | + |
| 21 | +```python |
| 22 | +def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: |
| 23 | + |
| 24 | + m = len(dungeon) |
| 25 | + n = len(dungeon[0]) |
| 26 | + |
| 27 | + dungeon[-1][-1] = max(1, 1-dungeon[-1][-1]) |
| 28 | + |
| 29 | + for c in range(n-2, -1, -1): |
| 30 | + dungeon[m-1][c] = max(1, dungeon[m-1][c+1] - dungeon[m-1][c]) |
| 31 | + |
| 32 | + for r in range(m-2, -1, -1): |
| 33 | + dungeon[r][n-1] = max(1, dungeon[r+1][n-1] - dungeon[r][n-1]) |
| 34 | + |
| 35 | + |
| 36 | + for r in range(m-2, -1, -1): |
| 37 | + for c in range(n-2, -1, -1): |
| 38 | + dungeon[r][c] = max(1, min(dungeon[r+1][c]-dungeon[r][c], dungeon[r][c+1]-dungeon[r][c])) |
| 39 | + |
| 40 | + return dungeon[0][0] |
| 41 | +``` |
| 42 | + |
| 43 | + |
| 44 | +``` |
| 45 | +Runtime: 68 ms, faster than 92.22% of Python3 online submissions for Dungeon Game. |
| 46 | +Memory Usage: 15.2 MB, less than 68.46% of Python3 online submissions for Dungeon Game. |
| 47 | +``` |
0 commit comments