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.
原題連接:https://leetcode.com/problems/dungeon-game/description/
思路:
動態(tài)規(guī)劃。
要求英雄從起點(diǎn)出發(fā)最小的血量。
考慮極端情況弹惦,只有一個格子霜威。如果格子值val是負(fù)數(shù)埂淮,則英雄血量至少為1-val寄雀;如果是整數(shù)炒俱,則英雄只需要1點(diǎn)血量保證存活即可巷燥。
考慮2*2的grid赡盘,上面已經(jīng)算出了到達(dá)最后一個格子最少需要的血量,那么結(jié)合grid[0][1]和grid[1][0]缰揪,我們能推出這兩個格子至少需要的血量亡脑。
grid[0][0]可以從01和10推出。
從上面分析邀跃,我們可以用一個二維的life數(shù)組表示從當(dāng)前點(diǎn)走到右下角霉咨,英雄在當(dāng)前點(diǎn)需要的最少血量,最后遞推出的life[0][0]即是所求值拍屑。
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[][] life = new int[m][n];
life[m-1][n-1] = dungeon[m-1][n-1] < 0 ? 1-dungeon[m-1][n-1] : 1;
for (int i = m-2; i >= 0; i--) {
life[i][n-1] = dungeon[i][n-1] < life[i+1][n-1] ? life[i+1][n-1] - dungeon[i][n-1] : 1;
}
for (int j = n-2; j >= 0; j--) {
life[m-1][j] = dungeon[m-1][j] < life[m-1][j+1] ? life[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 next = Math.min(life[i+1][j], life[i][j+1]);
life[i][j] = dungeon[i][j] < next ? next - dungeon[i][j] : 1;
}
}
return life[0][0];
}