`

Leetcode - 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) -3 3
-5 -10 1
10 30 -5 (P)

Notes:

  • 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.
public class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        if (dungeon == null || dungeon.length == 0 || dungeon[0].length == 0)
            return 1;
        int rows = dungeon.length;
        int cols = dungeon[0].length;
        int[][] dp = new int[rows][cols];
        dp[rows - 1][cols - 1] = dungeon[rows - 1][cols - 1] > 0 ? 1 : (1 - dungeon[rows - 1][cols - 1]);
        int lastRow = rows - 1;
        int lastCol = cols - 1;
        for (int i = lastRow - 1; i >= 0; i--) {
            dp[i][lastCol] = Math.max(dp[i + 1][lastCol] - dungeon[i][lastCol], 1);
        }
        for (int j = lastCol - 1; j >= 0; j--) {
            dp[lastRow][j] = Math.max(dp[lastRow][j + 1] - dungeon[lastRow][j], 1);
        }
        for (int i = lastRow - 1; i >= 0; i--) {
            for (int j = lastCol - 1; j >= 0; j--) {
                dp[i][j] = Math.max(Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j], 1);
            }
        }
        return dp[0][0];
    }
}

 

 

分享到:
评论
2 楼 qb_2008 2015-04-21  
dp[i][j] 是能达到终点的该位置最小值,同时还要保证dp[i][j] >= 1。似乎只能从后往前遍历。
dp[i][j]达到终点所需的初始值最小,必然要求dp[i + 1][j]和dp[i][j + 1]到达终点所需的初始值
最小。
但反过来,如果dp[i][j]代表从起点到(i, j)处所需的最小起始值,因为还有一个在最小起始值
情况下的当前值。
比如一条路过来是(MinNeed = 1, Cur = 2), 另一条路过来是(MinNeed = 2, Cur = 30),
如果当前dungeon为0,看似应该选第一条,但如果路后面有dungeon为-30,就是第二条
全局更优。所以要用dp,只能从后往前遍历,这时MinNeed和Cur是同一个值。
1 楼 likesky3 2015-04-21  
挺简单的一道二维DP,但是实现时写递推式还是有些费神,还需要加强练习吧

相关推荐

Global site tag (gtag.js) - Google Analytics