LC174. Dungeon Game

Posted by freeCookie🍪 on January 12, 2017

LC174. 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.

这题题设好长哦。。。总之就是求从起点到终点呢能够保证每一步的HP值都大于0,起点的最小HP值是多少。

java solution

发现discuss的想法很好,从终点开始寻找,首先初始化最下和最右的HP值,然后每一步向左向上走到起点,每一步是能到其右下的最小值。

public class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        if(dungeon == null || dungeon.length == 0 || dungeon[0].length == 0)    return 0;
        int m = dungeon.length, n = dungeon[0].length;
        int[][] hp = new int[m][n];
        hp[m-1][n-1] = Math.max(1-dungeon[m-1][n-1], 1);
        for(int i = m-2; i >= 0; i--){
            hp[i][n-1] = Math.max(hp[i+1][n-1] - dungeon[i][n-1], 1);
        }
        for(int j = n-2; j >= 0; j--){
            hp[m-1][j] = Math.max(hp[m-1][j+1] - dungeon[m-1][j], 1);
        }
        for(int i = m-2; i>= 0; i--){
            for(int j = n-2; j>= 0; j--){
                int right = Math.max(hp[i+1][j] - dungeon[i][j], 1);
                int up = Math.max(hp[i][j+1] - dungeon[i][j], 1);
                hp[i][j] = Math.min(right, up);
            }
        }
        return hp[0][0];
    }
}

O(mn), O(mn)