174. Dungeon Game
這道題很有意思,是從后往前的dp,這道題其實(shí)一看就知道是dp,不過(guò)要從后往前去做還是有點(diǎn)難想到的。
class Solution(object):
def calculateMinimumHP(self, dungeon):
"""
:type dungeon: List[List[int]]
:rtype: int
"""
# dp[i][j] the minimum hp for i,j to go to the last block
if not dungeon:
return 0
d = dungeon
m = len(d)
n = len(d[0])
dp = [[sys.maxint for _ in range(n)] for _ in range(m)]
dp[m-1][n-1] = max(1, 1-d[m-1][n-1])
# initialize
for i in range(m-2, -1, -1):
dp[i][n-1] = max(1, dp[i+1][n-1] - d[i][n-1])
for j in range(n-2, -1, -1):
dp[m-1][j] = max(1, dp[m-1][j+1] - d[m-1][j])
# loop
for i in range(m-2, -1, -1):
for j in range(n-2, -1, -1):
down = max(1, dp[i+1][j] - d[i][j])
right = max(1, dp[i][j+1] - d[i][j])
dp[i][j] = min(down, right)
return dp[0][0]