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) is initially positioned in the top-left, and must fight his, through the dungeon T O rescue the princess.
The knight has an initial health point represented by a positive integer. Drops to 0 or below, he dies immediately.
Some of the rooms is guarded by demons, so the knight loses health (negative integers) upon entering these rooms ; Other rooms is either empty (0 ' s) or contain magic orbs that increase the knight ' s Health (positive int Egers).
In order to reach the princess as quickly as possible, the Knight decides to move only rightward or downward in each step.
Problem Solving Ideas:
DP problem, there are two ways of thinking:
Idea One: Dp[i][j] represents the minimum amount of blood required from the starting point to dungeon[i][j], but this idea of recursive equations is very difficult to write
Idea two: Dp[i][j] represents the minimum amount of blood required from dungeon[i][j] to the end point, using one-dimensional arrays, recursive equations
DP[J] = dungeon[i][j] >= math.min (dp[j + 1], dp[j])-1? 1:math.min (Dp[j + 1], dp[j])-DUNGEON[I][J]
Of course, you can also use the Dungeon[i][j] array instead of the dp[] array, Java implementation is as follows:
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] = Dunge On[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]; }
Java for Leetcode 174 Dungeon Game