|
| 1 | +# 174. Dungeon Game |
| 2 | + |
| 3 | +- Difficulty: Hard. |
| 4 | +- Related Topics: Binary Search, Dynamic Programming. |
| 5 | +- Similar Questions: Unique Paths, Minimum Path Sum, Cherry Pickup. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +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. |
| 10 | + |
| 11 | +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. |
| 12 | + |
| 13 | +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). |
| 14 | + |
| 15 | +In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. |
| 16 | + |
| 17 | +**Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.** |
| 18 | + |
| 19 | +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```. |
| 20 | + |
| 21 | +| | | | |
| 22 | +| -- | -- | -- | |
| 23 | +| -2 (K) | -3 | 3 | |
| 24 | +| -5 | -10 | 1 | |
| 25 | +| 10 | 30 | -5 (P) | |
| 26 | + |
| 27 | +**Note:** |
| 28 | + |
| 29 | +- The knight's health has no upper bound. |
| 30 | +- 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. |
| 31 | + |
| 32 | +## Solution |
| 33 | + |
| 34 | +```javascript |
| 35 | +/** |
| 36 | + * @param {number[][]} dungeon |
| 37 | + * @return {number} |
| 38 | + */ |
| 39 | +var calculateMinimumHP = function(dungeon) { |
| 40 | + var m = dungeon.length; |
| 41 | + var n = dungeon[0].length; |
| 42 | + var dp = Array(m + 1).fill(0).map(_ => Array(n + 1).fill(Number.MAX_SAFE_INTEGER)); |
| 43 | + var tmp = 0; |
| 44 | + |
| 45 | + dp[m][ n - 1] = 1; |
| 46 | + dp[m - 1][n] = 1; |
| 47 | + |
| 48 | + for (var i = m - 1; i >= 0; i--) { |
| 49 | + for (var j = n - 1; j >= 0; j--) { |
| 50 | + tmp = Math.min(dp[i][j + 1], dp[i + 1][j]) - dungeon[i][j]; |
| 51 | + dp[i][j] = tmp <= 0 ? 1 : tmp; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return dp[0][0]; |
| 56 | +}; |
| 57 | +``` |
| 58 | + |
| 59 | +**Explain:** |
| 60 | + |
| 61 | +nope. |
| 62 | + |
| 63 | +**Complexity:** |
| 64 | + |
| 65 | +* Time complexity : O(m*n). |
| 66 | +* Space complexity : O(m*n). |
0 commit comments