1. 程式人生 > >leetcode 174. Dungeon Game   完美世界秋招編程題2

leetcode 174. Dungeon Game   完美世界秋招編程題2

騎士救公主

2017年完美世界秋招的原題。

原題鏈接:https://leetcode.com/problems/dungeon-game/description/


騎士救公主,每個格子可能加血也可能減血。而且到達每個格子時的血量必須大於等於1,問騎士初始最小血量是多少才能保證救到公主。騎士每次只能往右和往左走。好像可以壓縮一下空間。。。。。。這裏就不給出了.

我當時是從左上往後考慮的,一直沒搞清楚。。。

class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        if (dungeon == null || dungeon.length == 0 || dungeon[0].length == 0) return 0;
    
    int m = dungeon.length;
    int n = dungeon[0].length;
        ///走到m,n時所需要的最少血量
        int[][] health = new int[m][n];
        ///最後是整數的話,只需要一滴血就行,負數的話就是1+血
        health[m-1][n-1] = Math.max(1,1-dungeon[m-1][n-1]);
        //最後一列
        for(int i = m-2; i>=0 ;i--)
            health[i][n-1] = Math.max(1,health[i+1][n-1] - dungeon[i][n-1]);
        ///最後一行
        for(int j = n-2; j>=0;j--){
            health[m-1][j] = Math.max(1,health[m-1][j+1] - dungeon[m-1][j]);
        }
        ///中間的格子
        for(int i = m-2; i>=0;i--){
            for(int j = n-2;j>=0;j--){
                int right = Math.max(1,health[i][j+1]-dungeon[i][j]);
                int down = Math.max(1,health[i+1][j] - dungeon[i][j]);
                health[i][j] = Math.min(down,right);
            }
        }
        return health[0][0];
    }
}

可以參考這個過程

dungeon

-2,-3,3
-5,-10,1
10,30,-5

From the Dungeon grid, we can simply compute health for the [last row][last column].

Now we get

?,?,?
?,?,?
?,?,6

Now because the knight can only move rightward or downward in each step, we can compute all the health value for last row from right to left using its rightward neighbor. we can also compute all the health value for last column from bottom to up using its downward neighbor.

?,?,2
?,?,5
1,1,6

Now, we can compute all the health value using its downward neighbor and rightward neighbor(we use the min value of these 2 health value).

7,5,2
6,11,5
1,1,6


leetcode 174. Dungeon Game 完美世界秋招編程題2