python
class CalculateMinimumHP:
"""
174. 地下城游戏
https://leetcode.cn/problems/dungeon-game/
"""
def solution(self, dungeon: List[List[int]]) -> int:
# 我们想计算左上⻆到右下⻆所需的最⼩⽣命值
m, n = len(dungeon), len(dungeon[0])
self.memo = [[-1 for _ in range(n)] for _ in range(m)]
return self.dp(dungeon, 0, 0)
def dp(self, grid, i, j):
"""
从 grid[i][j] 到达终点(右下⻆)所需的最少⽣命值
:param grid:
:param i:
:param j:
:return:
"""
m, n = len(grid), len(grid[0])
# base case
if i == m - 1 and j == n - 1:
return 1 if grid[i][j] >= 0 else -grid[i][j] + 1
if i == m or j == n:
return float('inf')
if self.memo[i][j] != -1:
return self.memo[i][j]
res = min(self.dp(grid, i, j+1),
self.dp(grid, i+1, j)) - grid[i][j]
self.memo[i][j] = 1 if res <= 0 else res
return self.memo[i][j]