LC 174


Solution to LeetCode 174 Dungeon Game.

LeetCode 174

Dungeon Game (Hard) [link]

The question asks for the minimum hp at K such that K can reach P. This is equivalent to ask the hp at K such that K has 1 hp at P. The recurrence relation of the minimum hp needed at (i.j).

dp[i][j] = min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j]

Since dp[i][j] can be non-positive, we have to keep it above 1.

dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j])

Base case: dp[m][n - 1] = dp[m - 1][n] = 1

Final answer: dp[0][0]

class Solution(object):
    def calculateMinimumHP(self, dungeon):
        """
        :type dungeon: List[List[int]]
        :rtype: int
        """
        m, n = len(dungeon), len(dungeon[0])
        BIG = float('inf')

        dp = [[BIG] * (n + 1) for _ in range(m + 1)]
        dp[m][n - 1] = dp[m - 1][n] = 1  

        for i in range(m - 1, -1, -1):
            for j in range(n - 1, -1, -1):
                res = min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]
                dp[i][j] = max(res, 1)

        return dp[0][0]
        

  TOC