Wednesday, March 11, 2015

Dungeon Game

Q:
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.
A:
就是简单的2D  , 但是,这里要backward calculating

每个A[i][j] 表示的是这个位置需要多少engergy进来。但是由于前面的位置不允许出来的engergy<=0    ---------》 A[i][j] > 0

比较tricky的是: 要注意每次出去的生命值不能<=0  亦即每个位置剩余的生命必须>0

public class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        int m = dungeon.length, n = dungeon[0].length;
        
        int[][] A = new int[m+1][n+1];// A[i][j] is the minimun engery needed when entering
        Arrays.fill(A[m],Integer.MAX_VALUE);
        for(int i = 0;i<=m;i++)
            A[i][n] = Integer.MAX_VALUE;
        A[m-1][n] = 1;// the minimun ennergy at after princess was saved.  // or A[m][n-1] = 1;
        
        for(int i= m-1;i>=0;i--){
            for(int j = n-1;j>=0;j--){
                A[i][j] = Math.min(A[i+1][j], A[i][j+1]) - dungeon[i][j];
                if(A[i][j] <= 0)
                    A[i][j] = 1;
            }
        }
        return A[0][0];
    }
}


重新写了一遍。 这次直接在dungeon[][]上面改,没有用额外的空间。

public class Solution {
    public int calculateMinimumHP(int[][] A) {
        int m = A.length, n = A[0].length;
        A[m-1][n-1] = Math.max(1,1-A[m-1][n-1]);// here 1 is the minimum life engery after saving princess
        for(int j = n-2;j>=0;j--)//deal with the last row
            A[m-1][j] = Math.max(1,A[m-1][j+1] - A[m-1][j] );
        
        for(int i= m-2;i>=0;i--)
            for(int j = n-1;j>=0;j--)
                A[i][j] = Math.max(1,Math.min(A[i+1][j], j==n-1?Integer.MAX_VALUE:A[i][j+1]) - A[i][j]);
        return A[0][0];
    }
}




Mistakes:
1: 一开始A[i][j]的定义不清楚。
2: 忘了检查A[i][j] >0



No comments:

Post a Comment