classSolution:defcalculateMinimumHP(self,dungeon: List[List[int]]) ->int: n =len(dungeon) m =len(dungeon[0]) hp = [[0] * m for _ inrange(n)] #dp#初始化,处理边界#终点 need =1- dungeon[n-1][m-1] hp[n-1][m-1] = need if need >0else1#右边界for i inrange(n-2, -1, -1): need = hp[i+1][m-1] - dungeon[i][m-1] hp[i][m-1] = need if need >0else1#下边界for j inrange(m-2, -1, -1): need = hp[n-1][j+1] - dungeon[n-1][j] hp[n-1][j] = need if need >0else1#其他区域for i inrange(n-2, -1, -1):for j inrange(m-2, -1, -1): need =min(hp[i+1][j], hp[i][j+1])- dungeon[i][j] hp[i][j] = need if need >0else1return hp[0][0]
右侧和下侧增加辅助边hp=无穷大,可以简化处理边界的代码
classSolution:defcalculateMinimumHP(self,dungeon: List[List[int]]) ->int: n =len(dungeon) m =len(dungeon[0]) hp = [[sys.maxsize] * (m+1) for _ inrange(n+1)] #dp#辅助求终点hp hp[n][m-1] = hp[n-1][m] =1for i inrange(n-1, -1, -1):for j inrange(m-1, -1, -1): need =min(hp[i+1][j], hp[i][j+1])- dungeon[i][j] hp[i][j] = need if need >0else1return hp[0][0]