Dungeon Game
来源:互联网 发布:网络信息监测 编辑:程序博客网 时间:2024/06/06 06:32
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
.
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) {const int M = dungeon.size();if (0 == M) return 0;const int N = dungeon[0].size();vector<int> dp(N, 0);for (int i = M-1; i >= 0; i--)for (int j = N-1; j >= 0; j--){int nextHP = INT_MAX;if (i+1 == M && j+1 == N)nextHP = 0;else {if (i+1 <= M-1)nextHP = min(nextHP, dp[j]);if (j+1 <= N-1)nextHP = min(nextHP, dp[j+1]);}if (dungeon[i][j] >= nextHP )dp[j] = dungeon[i][j]>=1 ? 0:1;else {int tmp = nextHP-dungeon[i][j];dp[j] = (tmp+dungeon[i][j]) >= 1 ? tmp : (tmp+1); }}return dp[0]>0 ? dp[0]:1;}};
If returning dp[0] directly will fail, the knight have to have hp at initial state. for instance test case is "[100] ", you should return 1 not 0.
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- Dungeon Game
- EXTJS 组件开发(完整例子)
- Tomcat7新特性及兼容性考虑
- curl_easy_setopt函数介绍
- ceph一些基础概念的简介
- Android发送短信
- Dungeon Game
- http_load基准测试(整站式测试)
- Linux内核调优之Sysctl研究
- 关于Fragment使用的一些见解
- 为啥富人越富穷人越穷
- JNI使用流程及简单例子
- 《深入理解Python》读书笔记Ⅲ
- No 'Access-Control-Allow-Origin' header is present on the requested resource. 报错解决。
- Hadoop Windows下的问题