[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)-33
-5-101
1030-5 (P)

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.

Thought process:
Dynamic programming. 
  1. Sub-problem: 
    1. Determine the knight's minimum initial health so that he's able to reach dungeon[i][j].
    2. For every step the knight makes, his health cannot drop to zero. It's hard to iterate from the top-left corner because we don't know if we need to increase our initial health. Iterating from the bottom-right to top-left will solve this issue.
  2. Function: 
    1. If min(f[i + 1][j], f[i][j + 1]) - dungeon[i][j] >= 0: f[i][j] = this result.
    2. Else, f[i][j] = 1.
  3. Initialization: fill f with infinity. Initialize the right and bottom cells of f[m][n] to be 1.
  4. Answer: f[0][0].

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        int m = dungeon.length;
        int n = dungeon[0].length;
        int[][] f = new int[m + 1][n + 1];
        for (int i = 0; i <= m; i++) {
            Arrays.fill(f[i], Integer.MAX_VALUE);
        }
        f[m][n - 1] = 1;
        f[m - 1][n] = 1;
        
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                int health = Math.min(f[i + 1][j], f[i][j + 1]) - dungeon[i][j];
                f[i][j] = health > 0 ? health : 1;
            }
        }
        return f[0][0];
    }
}

Time complexity: O(mn).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee