|
| 1 | +/** |
| 2 | + * 174. Dungeon Game |
| 3 | + * https://leetcode.com/problems/dungeon-game/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. |
| 7 | + * The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially |
| 8 | + * positioned in the top-left room and must fight his way through dungeon to rescue the princess. |
| 9 | + * |
| 10 | + * The knight has an initial health point represented by a positive integer. If at any point his |
| 11 | + * health point drops to 0 or below, he dies immediately. |
| 12 | + * |
| 13 | + * Some of the rooms are guarded by demons (represented by negative integers), so the knight loses |
| 14 | + * health upon entering these rooms; other rooms are either empty (represented as 0) or contain |
| 15 | + * magic orbs that increase the knight's health (represented by positive integers). |
| 16 | + * |
| 17 | + * To reach the princess as quickly as possible, the knight decides to move only rightward or |
| 18 | + * downward in each step. |
| 19 | + * |
| 20 | + * Return the knight's minimum initial health so that he can rescue the princess. |
| 21 | + * |
| 22 | + * Note that any room can contain threats or power-ups, even the first room the knight enters and |
| 23 | + * the bottom-right room where the princess is imprisoned. |
| 24 | + */ |
| 25 | + |
| 26 | +/** |
| 27 | + * @param {number[][]} dungeon |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +var calculateMinimumHP = function(dungeon) { |
| 31 | + const dp = new Array(dungeon.length).fill(0).map(() => new Array(dungeon[0].length).fill(0)); |
| 32 | + return traverse(dungeon, dungeon.length, dungeon[0].length, 0, 0, dp); |
| 33 | +}; |
| 34 | + |
| 35 | +function traverse(dungeon, i, j, row, col, dp) { |
| 36 | + if (row === i - 1 && col === j - 1) { |
| 37 | + return Math.max(1, 1 - dungeon[row][col]); |
| 38 | + } else if (row >= i || col >= j) { |
| 39 | + return Infinity; |
| 40 | + } else if (dp[row][col]) { |
| 41 | + return dp[row][col]; |
| 42 | + } |
| 43 | + const right = traverse(dungeon, i, j, row, col + 1, dp); |
| 44 | + const down = traverse(dungeon, i, j, row + 1, col, dp); |
| 45 | + dp[row][col] = Math.max(1, Math.min(right, down) - dungeon[row][col]); |
| 46 | + return dp[row][col]; |
| 47 | +}; |
0 commit comments