[LeetCode] Dungeon Game
来源:互联网 发布:mac唇线笔 编辑:程序博客网 时间:2024/06/06 03:12
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
.
动态规划:
这道题要从后往前dp 不能从前往后 不然找不到状态转化方程
状态转换方程:dp[i][j]=Math.max(0, Math.min(dp[i+1][j],dp[i][j+1])-dungeon[i][j]);
public class Solution {//这道题要从后往前dp 不能从前往后 不然找不到状态转化方程//dp[i][j]=Math.max(0, Math.min(dp[i+1][j],dp[i][j+1])-dungeon[i][j]); public int calculateMinimumHP(int[][] dungeon) { if(dungeon.length==0||dungeon[0].length==0) return 0; int m=dungeon.length,n=dungeon[0].length; int[][] dp=new int[m][n]; dp[m-1][n-1]=dungeon[m-1][n-1]>=0?0:-dungeon[m-1][n-1]; for(int i=dungeon[0].length-2;i>=0;i--){dp[m-1][i]=dp[m-1][i+1]-dungeon[m-1][i];if(dp[m-1][i]<0) dp[m-1][i]=0; } for(int i=dungeon.length-2;i>=0;i--){ dp[i][n-1]=dp[i+1][n-1]-dungeon[i][n-1]; if(dp[i][n-1]<0) dp[i][n-1]=0; } for(int i=dungeon.length-2;i>=0;i--){ for(int j=dungeon[0].length-2;j>=0;j--){ int temp=Math.min(dp[i+1][j],dp[i][j+1]); dp[i][j]=Math.max(0, temp-dungeon[i][j]); } } return dp[0][0]+1; }}
- [leetcode] Dungeon Game
- leetcode 174: Dungeon Game
- [leetcode 174] Dungeon Game
- [leetcode] Dungeon Game
- Leetcode Dungeon Game
- LeetCode Dungeon Game
- LeetCode: Dungeon Game
- [LeetCode] Dungeon Game
- [leetcode] Dungeon Game
- LeetCode Dungeon Game
- [LeetCode]Dungeon Game
- Leetcode OJ Dungeon Game
- Leetcode: Dungeon Game
- leetcode dungeon game
- [leetcode]Dungeon Game
- LeetCode(174) Dungeon Game
- LeetCode 174 Dungeon Game
- LeetCode - Dungeon Game
- Java8集合源码解析-HashMap
- 网站分析
- pyspark开发环境搭建
- android sutdio版本和gradle版本的对应关系及as报错的处理Error:Failed to open zip file. Gradle's dependency cache ...
- 公有IP和私有IP介绍
- [LeetCode] Dungeon Game
- 使用注解的方式玩转MyBatis
- C++读入字符串的方法
- Java小案例——使用双重for循环实现杨辉三角的输出
- 进程池、线程池、内存池
- linux中shell 特殊变量$0 $n $* $@ $! $?的详解
- 项目笔记---项目一:超市管理系统
- Codeforces Round #376 (Div. 2) F. Video Cards —— 前缀和 & 后缀和
- 手机系统ROM开发中的电话号码格式客制化