# Hard-题目43：174. Dungeon Game

141人阅读 评论(0)

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.

class Solution {
public:
int calculateMinimumHP(vector<vector<int> > &dungeon) {
if(dungeon.empty())
return 0;
vector<vector<int> > dp(dungeon.size());
for(int i = 0; i < dp.size(); i++) {
dp[i].reserve(dungeon[i].size());
}
int m = dungeon.size();
int n = dungeon[0].size();
if(dungeon[m - 1][n - 1] >= 0) {
dp[m - 1][n - 1] = 1;
} else {
dp[m - 1][n - 1] = 1 - dungeon[m - 1][n - 1];
}

for(int i = m - 2; i >= 0; i--) {
dp[i][n - 1] = max(dp[i + 1][n - 1] - dungeon[i][n - 1], 1);
}
for(int j = n - 2; j >= 0; j--) {
dp[m - 1][j] = max(dp[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--) {
dp[i][j] = max(min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j], 1);
}
}

return dp[0][0];
}

};

8ms,100.00%,16ms,65.51%
Cmershen的碎碎念：

0
0

【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐（算法+实战）--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：55402次
• 积分：3192
• 等级：
• 排名：第10658名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论