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.

解题思路:

dp问题,有两种思路:

思路一:dp[i][j]表示从起点到dungeon[i][j]所需的最小血量,但是这种思路递推方程非常不好写

思路二:dp[i][j]表示从dungeon[i][j]到终点所需的最小血量,使用一维数组即可,递推方程

dp[j] = dungeon[i][j] >= Math.min(dp[j + 1], dp[j]) - 1 ? 1: Math.min(dp[j + 1], dp[j]) - dungeon[i][j]

当然,也可以直接用dungeon[i][j]数组替代dp[]数组,JAVA实现如下:

    public int calculateMinimumHP(int[][] dungeon) {
int[] dp = new int[dungeon[0].length];
dp[dungeon[0].length - 1] = dungeon[dungeon.length - 1][dungeon[0].length - 1] >= 0 ? 1
: 1 - dungeon[dungeon.length - 1][dungeon[0].length - 1];
for (int i = dungeon[0].length - 2; i >= 0; i--)
dp[i] = dungeon[dungeon.length - 1][i] >= dp[i + 1] - 1 ? 1
: dp[i + 1] - dungeon[dungeon.length - 1][i];
for (int i = dungeon.length - 2; i >= 0; i--) {
dp[dungeon[0].length - 1] = dungeon[i][dungeon[0].length - 1] >= dp[dungeon[0].length - 1] - 1 ? 1
: dp[dungeon[0].length - 1]
- dungeon[i][dungeon[0].length - 1];
for (int j = dungeon[0].length - 2; j >= 0; j--)
dp[j] = dungeon[i][j] >= Math.min(dp[j + 1], dp[j]) - 1 ? 1
: Math.min(dp[j + 1], dp[j]) - dungeon[i][j];
}
return dp[0];
}

最新文章

  1. Ubuntu虚拟机中断后重启网络断接错误解决方案
  2. Python 自动化入门 day1复习
  3. jQuery文本段落展开和折叠效果
  4. UnicodeDecodeError: 'utf8' codec can't decode
  5. 深入浅出Mybatis-与Spring集成
  6. Android图像处理1
  7. 使用react-native做一个简单的应用-06商品界面的实现
  8. 利用@media screen实现网页布局的自适应,@media screen and
  9. Swift学习(1)
  10. Java-NIO(九):管道 (Pipe)
  11. 深入理解.net - 2.多态 Polymorphsim
  12. Codeforces Round #554 (Div. 2)自闭记
  13. expected_conditions模块提供了判断页面元素的16种方法
  14. Linux---一级/二级目录以及位置目录名/指令
  15. 高并发下的Id生成器
  16. boost 正则表达式 regex
  17. python全栈开发 * 32知识点汇总 * 180717
  18. ElasticSearch 6.x 父子文档[join]分析
  19. python学习之老男孩python全栈第九期_day015作业_老男孩Python全9期练习题(面试真题模拟)
  20. docker 端口映射错误解决方法

热门文章

  1. golang thrift 总结一下网络上的一些坑
  2. MVC传值汇总
  3. TCP/IP详解 学习六
  4. 网页设计师常用的PHOTOSHOP插件
  5. jsp学习一
  6. 自动打包iOS项目
  7. python urllib2使用心得
  8. MyEclipse使用SVN进行项目版本控制
  9. Spring MVC:使用SimpleUrlHandlerMapping的一个简单例子
  10. tmux 快捷键