Leetcode 174. Dungeon Game

Problem

The demons had captured the princess 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 was initially positioned in the top-left room and must fight his way through 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 (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight’s health (represented by positive integers).

To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.

Return the knight’s minimum initial health so that he can rescue the princess.

Note that 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.

Algorithm

DP. Run the dynamics programming in inverse direction and if the health point is lower than 1 update it to 1.

Code

class Solution:
    def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
        rows = len(dungeon)
        cols = len(dungeon[0])
        ans = [[40000001 for x in range(cols+1)] for y in range(rows+1)]
        ans[rows][cols-1], ans[rows-1][cols] = 1, 1
        for r in range(rows-1, -1, -1):
            for c in range(cols-1, -1, -1):
                val = min(ans[r+1][c], ans[r][c+1])
                if dungeon[r][c] < 0:
                    ans[r][c] = val - dungeon[r][c]
                elif val > dungeon[r][c]:
                    ans[r][c] = val - dungeon[r][c]
                else:
                    ans[r][c] = 1
        
        return ans[0][0]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值