Leetcode-174. Dungeon Game 地下城游戏 (DP)
题目
一些恶魔抓住了公主(P)并将她关在了地下城的右下角。地下城是由 M x N 个房间组成的二维网格。我们英勇的骑士(K)最初被安置在左上角的房间里,他必须穿过地下城并通过对抗恶魔来拯救公主。
骑士的初始健康点数为一个正整数。如果他的健康点数在某一时刻降至 0 或以下,他会立即死亡。
有些房间由恶魔守卫,因此骑士在进入这些房间时会失去健康点数(若房间里的值为负整数,则表示骑士将损失健康点数);其他房间要么是空的(房间里的值为 0),要么包含增加骑士健康点数的魔法球(若房间里的值为正整数,则表示骑士将增加健康点数)。
为了尽快到达公主,骑士决定每次只向右或向下移动一步。
链接:https://leetcode.com/problems/dungeon-game/
The demons had captured the princess § and im*ed 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.
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.
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).
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Write a function to determine the knight’s minimum initial health so that he is able to rescue the princess.
Note:
- The knight’s health has no upper bound.
- Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is im*ed.
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.
思路及代码
DP
- health[i][j]:到达i,j前所需的最低血量(最低为1)
- health[i][j] = max(min(health[i+1][j],health[i][j+1]) - dungeon[i][j], 1)
- 其中min(health[i+1][j],health[i][j+1])表示可以向下走或者向右走,选一个所需最低血量最少的路
- max(…, 1)表示若血量低于1则取1为最低血量
- 初始值: health[m-1][n-1] = max(1 - dungeon[m-1][n-1],1)
class Solution:
def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
m = len(dungeon)
n = len(dungeon[0])
health = [[0 for i in range(n)] for j in range(m)]
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
if i != m-1 and j != n-1:
health[i][j] = max(min(health[i+1][j],health[i][j+1]) - dungeon[i][j], 1)
elif i == m-1 and j == n-1:
health[i][j] = max(1 - dungeon[i][j],1)
elif i == m-1:
health[i][j] = max(health[i][j+1] - dungeon[i][j], 1)
else: # j == n-1
health[i][j] = max(health[i+1][j] - dungeon[i][j], 1)
return health[0][0]
复杂度
T =
S =
上一篇: Leetcode174. 地下城游戏——动态规划的无后效性
下一篇: 一些JS基础知识整理
推荐阅读