leetcode 174. 地下城游戏

题目链接:leetcode

思路:

  • 使用动态规划,knight的生命值最少为1
  • 初始条件,dp[-1][-1] = max(1-dungeon[-1][-1],1);
    dp[i][-1] = max(dp[i+1][-1]-dungeon[i][-1],1)
    dp[-1][j] = max(dp[-1][j+1] -dungeon[-1][j],1)
  • 转移方程,dp[i][j] = max(min(dp[i+1][j],dp[i][j+1])-dungeon[i][j],1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
def calculateMinimumHP(self, dungeon):
"""
:type dungeon: List[List[int]]
:rtype: int
"""
#dp[i][j]
if not dungeon or not dungeon[0]:return 0
m,n = len(dungeon),len(dungeon[0])
dp = [[0]*n for _ in range(m)]
dp[-1][-1] = max(1-dungeon[-1][-1],1)
for i in range(m-2,-1,-1):
dp[i][n-1] = max(dp[i+1][n-1]-dungeon[i][n-1],1)

for j in range(n-2,-1,-1):
dp[m-1][j] = max(dp[m-1][j+1] -dungeon[m-1][j],1)

for i in range(m-2,-1,-1):
for j in range(n-2,-1,-1):
dp[i][j] = max(min(dp[i+1][j],dp[i][j+1])-dungeon[i][j],1)
return dp[0][0]