题目描述:
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.
一个矩阵游戏。骑士从左上角走到右下角,过程中会遇到怪物或加血,以正负值表示。求骑士到达右下角所需的最小血量。
本题最直接的思路是DFS,从左上开始,状态转移无非是向右或向下(边界值允许的情况下):
Dfs (row + 1, col);
Dfs (row , col + 1);
不够高效,会导致运行超时。
实现代码:
public class Solution {
private List<int> _result;
private int _row;
private int _col;
public int CalculateMinimumHP(int[,] dungeon)
{
_result = new List<int>();
_row = dungeon.GetLength(0);
_col = dungeon.GetLength(1);
Dfs(dungeon, 0,0,0,0);
var min = _result.Min();
return min;
}
public void Dfs(int[,] game, int r, int c, int minHp, int hp)
{
hp += game[r,c];
if(hp <= 0 && hp < minHp){
minHp = hp ;
}
// check ending
if((r == _row-1) && (c == _col-1)){
if(minHp < 0){
_result.Add(1-minHp);
}else{
_result.Add(1);
}
return ;
}
if (r < _row - 1){
Dfs(game, r + 1, c, minHp, hp);
}
if (c < _col - 1){
Dfs(game, r, c + 1, minHp, hp);
}
}
}
解法二:
使用dp。从右下角考虑所需最小血量,minHp[row-1,col-1] = Math.Max(1-dungeon[row-1,col-1],1);
初始化边界值。
向上走或向左走,取最小值:
dp[i,j] = Min(dp[i+1,j]-dungeon[i+1,j], dp[i,j+1]-dungeon[i,j])
dp[0,0]为解。
实现代码:
public class Solution {
public int CalculateMinimumHP(int[,] dungeon)
{
var row = dungeon.GetLength(0);
var col = dungeon.GetLength(1);
// the min hp to have
var dp = new int[row, col];
dp [row-1, col-1] = MinHp(1- dungeon[row-1,col-1]);
// set last row
for (var i = col - 2;i >= 0; i--){
dp[row-1,i] = MinHp(dp[row-1,i+1] - dungeon[row-1,i]);
}
// set last col
for (var i = row - 2;i >= 0; i--){
dp[i,col-1] = MinHp(dp[i+1,col-1] - dungeon[i,col-1]);
}
for (var i = row-2;i >= 0;i --){
for (var j = col - 2; j >= 0; j--){
// come down or right
dp[i,j] = Math.Min(MinHp(dp[i+1,j] - dungeon[i,j]),MinHp(dp[i,j+1] -dungeon[i,j]));
}
}
return dp[0,0];
}
private int MinHp(int x){
return Math.Max(x, 1);
}
}