C++实现LeetCode(174.地牢游戏)
[LeetCode] 174. Dungeon Game 地牢游戏
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) |
- 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.
1 (K) | -3 | 3 |
0 | -2 | 0 |
-3 | -3 | -3 (P) |
解法一:
class Solution {public:int calculateMinimumHP(vector>& dungeon) {int m = dungeon.size(), n = dungeon[0].size(); vector > dp(m + 1, vector (n + 1, INT_MAX)); dp[m][n - 1] = 1; dp[m - 1][n] = 1; for (int i = m - 1; i >= 0; --i) {for (int j = n - 1; j >= 0; --j) {dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]); }}return dp[0][0]; }};
我们可以对空间进行优化,使用一个一维的 dp 数组,并且不停的覆盖原有的值,参见代码如下:
解法二:
class Solution {public:int calculateMinimumHP(vector>& dungeon) {int m = dungeon.size(), n = dungeon[0].size(); vector dp(n + 1, INT_MAX); dp[n - 1] = 1; for (int i = m - 1; i >= 0; --i) {for (int j = n - 1; j >= 0; --j) {dp[j] = max(1, min(dp[j], dp[j + 1]) - dungeon[i][j]); }}return dp[0]; }};
【C++实现LeetCode(174.地牢游戏)】到此这篇关于C++实现LeetCode(174.地牢游戏)的文章就介绍到这了,更多相关C++实现地牢游戏内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Node.js中readline模块实现终端输入
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- java中如何实现重建二叉树
- leetcode|leetcode 92. 反转链表 II
- 人脸识别|【人脸识别系列】| 实现自动化妆