The Dungeon Game coding problem is a grid-based challenge where a knight must rescue a princess. The knight starts at the top-left corner of a dungeon (a 2D grid) and needs to reach the princess at the bottom-right. Each cell contains an integer: positive values increase the knight's health, while negative values decrease it. If the knight's health ever drops to 0 or below, he dies immediately. The goal is to find the minimum initial health the knight needs to survive the journey.
Companies like Uber and Amazon ask the Dungeon Game interview question to test a candidate's mastery of dynamic programming interview pattern, especially when the standard "top-down" approach is insufficient. In this problem, calculating health from the start doesn't work because future cells influence current requirements. It requires "reverse DP," teaching candidates to think about problems from the destination back to the source.
This problem is solved using Dynamic Programming (Bottom-Up from Destination).
dp[i][j] as the minimum health needed before entering cell (i, j).(i, j) must be at least 1.dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j]).dp[0][0].Suppose we have a 2x2 grid:
[-2, -3]
[-5, 10]
Princess is at (1, 1) with value 10.
(1, 1) is 1. Health needed before (1, 1): max(1, 1 - 10) = 1.(0, 1) (value -3): needs to reach (1, 1) (needs 1). max(1, 1 - (-3)) = 4.(1, 0) (value -5): needs to reach (1, 1) (needs 1). max(1, 1 - (-5)) = 6.(0, 0) (value -2): can go to (0, 1) (needs 4) or (1, 0) (needs 6). Pick (0, 1).
Health before (0, 0): max(1, 4 - (-2)) = 6.
Result: 6.Whenever a pathfinding problem depends on future states to determine the current best choice, try solving it backwards from the goal. This is a very common trick in competitive programming and advanced technical interviews.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Cherry Pickup II | Hard | Solve | |
| Minimum Falling Path Sum II | Hard | Solve | |
| Cherry Pickup | Hard | Solve | |
| Maximum Vacation Days | Hard | Solve | |
| Check if There Is a Valid Parentheses String Path | Hard | Solve |