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: MEDIUM_HARD
Tags: Matrices

Dynamic programming

Data structures
Skill types: Dynamic programming

Data structures

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

Solutions:
class Solution:

	def calculateMinimumHP(self, dungeon):
		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):
		(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]
				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
				dp[i][j] = max(1, dp[i][j])
		return dp[0][0]


class Solution:

	def calculateMinimumHP(self, dungeon):
		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):
		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]


class Solution:

	def calculateMinimumHP(self, dungeon):
		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):
		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):
		(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):
		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):
		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):
		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])