table.dungeon, .dungeon th, .dungeon td {
  border:3px solid black;
}

 .dungeon th, .dungeon td {
    text-align: center;
    height: 70px;
    width: 70px;
}

The demons had captured the princess (P) and imprisoned 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.

For 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.


       
               
                       -2 (K)
                       -3
                       3
               
               
                       -5
                       -10
                       1
               
               
                       10
                       30
                       -5 (P)
               
       


 

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 imprisoned.

Difficulty: interview

Starter code:

class Solution:
    def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
        

Solutions:
class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         '''
         逆回，当是小于等于0时，是相反数+1.   dp为到当前i,j只要需要的点数， 最小为1，保证 活着
         
         r,  c   r   ,c+1
         r+1,c   r+1,c+1
         
         r,c处至少的点数 - r,c处惩罚点数  是  其下面和右面最少需要的点数，  也就是第33行
         
         '''
         row = len(dungeon)
         col = len(dungeon[0])
         dp = [[0 for  c in range(col)] for r in range(row)]
         if dungeon[-1][-1] <= 0:
             dp[-1][-1] = -dungeon[-1][-1] + 1
         else:
             dp[-1][-1] = 1
         for r in range(row-2,-1,-1):
             dp[r][-1] = dp[r+1][-1]  - dungeon[r][-1]
             if dp[r][-1] <= 0:
                 dp[r][-1] = 1
         for c in range(col-2,-1,-1):
             dp[-1][c] = dp[-1][c+1]  - dungeon[-1][c]
             if dp[-1][c] <= 0:
                 dp[-1][c] = 1
         for r in range(row-2,-1,-1):
             for c in range(col-2,-1,-1):
                 dp[r][c] = min(dp[r+1][c],dp[r][c+1]) - dungeon[r][c]
                 if dp[r][c] <= 0:
                     dp[r][c] = 1
         return dp[0][0]


class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
 
         # sol1: DP, choose the safest path
         # http://leetcodesolution.blogspot.kr/2015/01/leetcode-dungeon-game.html
         # minInitHealth[i][j] = min(minInitHealth[i+1][j], minInitHealth[i][j+1]) - dungeon[i][j]
         # set minInitHealth[i][j] to 1 if < 1
         M, N = len(dungeon), len(dungeon[0])
         dp = [[0] * N for _ in range(M)]
         for i in reversed(list(range(M))):
             for j in reversed(list(range(N))):
                 v = dungeon[i][j]
                 # choose right/down, which requires less
                 if i == M - 1 and j == N - 1:
                     dp[i][j] = 1 - v
                 elif i == M - 1:
                     dp[i][j] = dp[i][j + 1] - v
                 elif j == N - 1:
                     dp[i][j] = dp[i + 1][j] - v
                 else:
                     dp[i][j] = min(dp[i + 1][j], dp[i][j + 1]) - v
                 # always ensure >= 1
                 dp[i][j] = max(1, dp[i][j])
         return dp[0][0]


class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         m=len( dungeon)  
         n=len( dungeon[0])
         
         dp=[[float('inf') for _ in range(n+1)] for _ in range(m+1)]
         dp[m][n-1]=1
         dp[m-1][n]=1
         
         for i in range(m-1,-1,-1):
             for j in range(n-1,-1,-1):
                 
                 need =min(dp[i+1][j],dp[i][j+1])-dungeon[i][j]
                 if need <=0:
                     need=1
                 dp[i][j]=need 
         return dp[0][0]        

class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         n = len(dungeon[0])
         need = [2**31] * (n-1) + [1]
         for row in dungeon[::-1]:
             for j in range(n)[::-1]:
                 need[j] = max(min(need[j:j+2]) - row[j], 1)
         return need[0]

class Solution:
     def calculateMinimumHP(self, dungeon):
         if not dungeon or not dungeon[0]:
             return 1
         dp = [[0 for i in range(len(dungeon[0]))] for i in range(len(dungeon))]
         dp[-1][-1] = 1 - dungeon[-1][-1]
         row = len(dungeon)
         column = len(dungeon[0])
         for i in range(1,row):
             dp[row-1-i][-1] = max(1 - dungeon[row-1-i][-1], dp[row-i][-1] - dungeon[row-1-i][-1])
         for i in range(1,column):
             dp[-1][column-1-i] = max(1 - dungeon[-1][column-1-i], dp[-1][column-i] - dungeon[-1][column-1-i])
         for i in range(1,row):
             for j in range(1,column):
                 dp[row-1-i][column-1-j] = max(1 - dungeon[row-1-i][column-1-j], min(dp[row-i][column-1-j],dp[row-1-i][column-j]) - dungeon[row-1-i][column-1-j])
         if dp[0][0] <= 0:
             return 1
         return dp[0][0]
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """


class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         num_rows = len(dungeon)
         num_cols = len(dungeon[0])
         INF = float('inf')
         for ri in range(num_rows - 1, -1, -1):
             for ci in range(num_cols - 1, -1, -1):
                 if ri == num_rows - 1 and ci == num_cols - 1:
                     need = -dungeon[ri][ci] + 1
                 else:
                     down = INF if ri == num_rows - 1 else dungeon[ri+1][ci]
                     right = INF if ci == num_cols - 1 else dungeon[ri][ci + 1]
                     need = min(down, right) - dungeon[ri][ci]
                 dungeon[ri][ci] = max(need, 1)
         return dungeon[0][0]


class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         best = [[0] * len(dungeon[0]) for x in range(0, len(dungeon))]
         for row in range(-1, -len(dungeon) - 1, -1):
             for col in range(-1, -len(dungeon[0]) - 1, -1):
                 needed = -dungeon[row][col]
                 nextSteps = []
                 if row < -1:
                     nextSteps.append(best[row + 1][col])
                 if col < -1:
                     nextSteps.append(best[row][col + 1])
                 if len(nextSteps) > 0:
                     needed += min(nextSteps)
                 needed = max(0, needed)
                 best[row][col] = needed
                 
         return best[0][0] + 1

class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         m,n =len(dungeon), len(dungeon[0])
         record=[[None]*n for i in range(m)]
         record[-1][-1]=max(1-dungeon[-1][-1], 1)
         for i in range(n-1)[::-1]:
             record[m-1][i]=max(1, record[m-1][i+1]-dungeon[m-1][i])
         for j in range(m-1)[::-1]:
             record[j][n-1]=max(1, record[j+1][n-1]-dungeon[j][n-1])
         
         for i in range(m-1)[::-1]:
             for j in range(n-1)[::-1]:
                 mina=max(record[i+1][j]-dungeon[i][j], 1)
                 minb=max(record[i][j+1]-dungeon[i][j], 1)
                 record[i][j]=min(mina,minb)
         return record[0][0]

class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         if not dungeon or not dungeon[0]:
             return 1
         
         m = len(dungeon)
         n = len(dungeon[0])
         
         dp = [None] * n
         
         for i in range(m - 1, -1, -1):
             for j in range(n - 1, -1, -1):
                 tmp = []
                 if i + 1 < m:
                     tmp.append(dp[j])
                 
                 if j + 1 < n:
                     tmp.append(dp[j + 1])
                 
                 minLeft = 1
                 if tmp:
                     minLeft = min(tmp)
                 
                 dp[j] = max(minLeft - dungeon[i][j], 1)
         
         return dp[0]

class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         n = len(dungeon)
         m = len(dungeon[0])
 
         for i in range(n-1, -1, -1):
             for j in range(m-1, -1, -1):
                 if i+1 < n and j+1 < m:
                     temp = max(dungeon[i+1][j], dungeon[i][j+1])
                 elif i+1 < n:
                     temp = dungeon[i+1][j]
                 elif j+1 < m:
                     temp = dungeon[i][j+1]
                 else:
                     temp = 0
                 print(temp)
                 dungeon[i][j] = dungeon[i][j] + temp
                 dungeon[i][j] = min(dungeon[i][j], 0)
         return(max(1, 1-dungeon[0][0]))

class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         m = len(dungeon)
         n = len(dungeon[0])
         dp = [0] * n
         dp[n-1] = max(1, 1 - dungeon[m-1][n-1])
         for i in range(m-1, -1, -1):
             for j in range(n-1, -1, -1):
                 if i == m-1 and j == n-1:
                     continue
                 if i == m-1:
                     dp[j] = max(1, dp[j+1] - dungeon[i][j])
                 elif j == n-1:
                     dp[j] = max(1, dp[j] - dungeon[i][j])
                 else:
                     dp[j] = max(1, min(dp[j], dp[j+1]) - dungeon[i][j])
         return dp[0]

class Solution:
     def calculateMinimumHP(self, dungeon):
         """
         :type dungeon: List[List[int]]
         :rtype: int
         """
         if not any(dungeon):
             return 1
         m = len(dungeon)
         n = len(dungeon[0])
         memo = {(m - 1, n - 1): 1}
         def helper(i, j):
             if (i, j) not in memo:
                 if i == m - 1:
                     ans = max(1, helper(i, j+1) - dungeon[i][j+1])
                 elif j == n - 1:
                     ans = max(1, helper(i+1, j) - dungeon[i+1][j])
                 else:
                     ans = min(max(1, helper(i, j+1) - dungeon[i][j+1]),
                              max(1, helper(i+1, j) - dungeon[i+1][j]))
                 memo[(i, j)] = ans
             return memo[(i, j)]
         return max(1, helper(0, 0) - dungeon[0][0])