Dynamic Programming - 174. Dungeon Game

5

174. Dungeon Game

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)-33
-5-101
1030-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.

思路:

题目意思是有一个骑士在网格的左上角,一个公主在右下角,每个网格中的数字如果是正代表给骑士加血,如果是负数就说明要扣血,题目要求找出骑士在开始的时候需要多少血量,才能救到公主。在做dp的题目的时候其实最难的就是抽象子问题,找出状态转移方程,剩下的都差不多。
这一题中最后一步是走到右下角,扣完网格中的血之后大于零就能就到公主,而最后一步只能从上面走下来和左边走到右边。所以子问题就是上一步留下的血量在当前网格扣完还能大于零。状态转移方程就是dp[i][j] = min(max(dp[i+1][j] - dungeon[i][j], 1), max(dp[i][j+1] - dungeon[i][j], 1)), 边界条件就是最左边一列和最后行不能通过状态转移方程求出。初始值就是右下角格子扣完血和1的最小值(可以用1减去当前网格然后和1求最大值)。

代码:

go:

func calculateMinimumHP(dungeon [][]int) int {
    m, n := len(dungeon), len(dungeon[0])

    for i := m - 1; i >= 0; i-- {
        for j := n -1; j >=0; j-- {
            if i == m - 1 && j == n - 1 {
                dungeon[i][j] =  max(1 - dungeon[i][j], 1)
            } else if i == m - 1 && j != n - 1 { // 只能往右,反推即为左
                dungeon[i][j] = max(dungeon[i][j+1] - dungeon[i][j], 1)
            } else if i != m -1 && j == n - 1 {
                dungeon[i][j] = max(dungeon[i+1][j] - dungeon[i][j], 1)
            } else {
                dungeon[i][j] = min(max(dungeon[i+1][j] - dungeon[i][j], 1), max(dungeon[i][j+1] - dungeon[i][j], 1))
            }
        }
    }
    
    return dungeon[0][0]
}

func min(i, j int) int {
    if i < j {
        return i
    }
    return j
}

func max(i, j int) int {
     if i > j {
        return i
    }
    return j
}