Introduction
In this article, we will sove the leetcode problem
#174, Dungeon Game. The problem statement goes like this:
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.
- static void Main(string[] args)
- {
- var result = calculateMinimumHP(new int[][]
- {
- new int[]{ -2, -3, 3 },
- new int[]{ -5, -10, 1 },
- new int[]{ 10, 30, -5 }
- });
-
- }
Solution
The best approach for problems like this is dynamic programming, in which we will find the value of each cell depending on the previously calculated cell value. So the algorithm basically goes like,
- We will take a empty 2d array of same dimensions as dungeon, and fill the last cell, i.e. dungeon[n-1][n-1].
- Then we will keep finding the health of the Knight(K) by traversing over the empty dungeon.
- First we will fill the last column(DOWN<--DOWN) and then, fill the last row(RIGHT<--RIGHT).
- And finally, we fill up the rest of the empty positions to get on to the 1st cell, i.e. health[0, 0].
Here is the C# code for the approach,
- static int calculateMinimumHP(int[][] dungeon)
- {
- if (dungeon == null || dungeon.Length == 0)
- {
- return 0;
- }
-
- int height = dungeon.Length;
- int width = dungeon[0].Length;
- int[,] health = new int[height, width];
- health[height - 1, width - 1] =
- (dungeon[height - 1][width - 1] > 0) ? 1 : 1 - dungeon[height - 1][width - 1];
-
-
- for (int i = height - 2; i >= 0; i--)
- {
- int temp = health[i + 1, width - 1] - dungeon[i][width - 1];
- health[i, width - 1] = Math.Max(1, temp);
- }
-
-
- for (int j = width - 2; j >= 0; j--)
- {
- int temp = health[height - 1, j + 1] - dungeon[height - 1][j];
- health[height - 1, j] = Math.Max(temp, 1);
- }
-
- for (int i = height - 2; i >= 0; i--)
- {
- for (int j = width - 2; j >= 0; j--)
- {
- int down = Math.Max(1, health[i + 1, j] - dungeon[i][j]);
- int right = Math.Max(1, health[i, j + 1] - dungeon[i][j]);
- health[i, j] = Math.Min(down, right);
- }
- }
-
- return health[0, 0];
- }