|
| 1 | +# https://leetcode.com/problems/dungeon-game/ |
| 2 | +# |
| 3 | +# The demons had captured the princess (P) and imprisoned her in the |
| 4 | +# bottom-right corner of a dungeon. The dungeon consists of M x N |
| 5 | +# rooms laid out in a 2D grid. Our valiant knight (K) was initially |
| 6 | +# positioned in the top-left room and must fight his way through the |
| 7 | +# dungeon to rescue the princess. |
| 8 | +# |
| 9 | +# The knight has an initial health point represented by a positive |
| 10 | +# integer. If at any point his health point drops to 0 or below, |
| 11 | +# he dies immediately. |
| 12 | +# |
| 13 | +# Some of the rooms are guarded by demons, so the knight loses health |
| 14 | +# (negative integers) upon entering these rooms; other rooms are |
| 15 | +# either empty (0's) or contain magic orbs that increase the knight's |
| 16 | +# health (positive integers). |
| 17 | +# |
| 18 | +# In order to reach the princess as quickly as possible, the knight |
| 19 | +# decides to move only rightward or downward in each step. |
| 20 | +# |
| 21 | +# Write a function to determine the knight's minimum initial health |
| 22 | +# so that he is able to rescue the princess. |
| 23 | +# |
| 24 | +# For example, given the dungeon below, the initial health of the |
| 25 | +# knight must be at least 7 if he follows the optimal path |
| 26 | +# RIGHT -> RIGHT -> DOWN -> DOWN. |
| 27 | +# |
| 28 | +# +-------+-------+-------+ |
| 29 | +# | | | | |
| 30 | +# | -2(K) | -3 | 3 | |
| 31 | +# | | | | |
| 32 | +# +-------+-------+-------+ |
| 33 | +# | | | | |
| 34 | +# | -5 | -10 | 1 | |
| 35 | +# | | | | |
| 36 | +# +-------+-------+-------+ |
| 37 | +# | | | | |
| 38 | +# | 10 | 30 | -5(P) | |
| 39 | +# | | | | |
| 40 | +# +-------+-------+-------+ |
| 41 | +# |
| 42 | +# Notes: |
| 43 | +# |
| 44 | +# + The knight's health has no upper bound. |
| 45 | +# + Any room can contain threats or power-ups, even the first room |
| 46 | +# the knight enters and the bottom-right room where the princess |
| 47 | +# is imprisoned. |
| 48 | + |
| 49 | + |
| 50 | +# @param {Integer[][]} dungeon |
| 51 | +# @return {Integer} |
| 52 | +def calculate_minimum_hp(dungeon) |
| 53 | + m, n = dungeon.size, dungeon[0].size |
| 54 | + dp = Array.new(m) { Array.new(n, 0) } |
| 55 | + |
| 56 | + dp[-1][-1] = [1 - dungeon[-1][-1], 1].max |
| 57 | + (m - 2).downto(0) { |i| dp[i][-1] = [dp[i + 1][-1] - dungeon[i][-1], 1].max } |
| 58 | + (n - 2).downto(0) { |j| dp[-1][j] = [dp[-1][j + 1] - dungeon[-1][j], 1].max } |
| 59 | + |
| 60 | + (m - 2).downto(0) do |i| |
| 61 | + (n - 2).downto(0) do |j| |
| 62 | + dp[i][j] = [ |
| 63 | + [dp[i + 1][j] - dungeon[i][j], 1].max, |
| 64 | + [dp[i][j + 1] - dungeon[i][j], 1].max |
| 65 | + ].min |
| 66 | + end |
| 67 | + end |
| 68 | + |
| 69 | + dp[0][0] |
| 70 | +end |
0 commit comments