Dungeon Game - Problem

Imagine a brave knight on a heroic quest to rescue a princess trapped in a dangerous dungeon! 🏰⚔️

The dungeon is represented as an m x n grid where each room contains either:

  • Demons (negative values) - damage the knight's health
  • Magic orbs (positive values) - restore the knight's health
  • Empty rooms (0) - no effect on health

The knight starts at the top-left corner [0,0] and must reach the princess at the bottom-right corner [m-1,n-1]. The knight can only move right or down at each step.

Critical Rule: If the knight's health drops to 0 or below at any point, he dies immediately! 💀

Your task is to determine the minimum initial health the knight needs to successfully rescue the princess, ensuring his health never drops to 0 or below during the journey.

Input & Output

example_1.py — Classic Dungeon
$ Input: [[-4,5,2],[1,-4,0]]
Output: 7
💡 Note: The optimal path is Right→Down→Right. Starting with 7 HP: at (-4) we have 3 HP, at (-4) we have 4 HP, at (0) we still have 4 HP. Any less initial health would cause death at some point.
example_2.py — Single Positive Cell
$ Input: [[1,2],[3,4]]
Output: 1
💡 Note: All rooms contain positive values or are empty, so we only need the minimum possible health of 1 to start with.
example_3.py — Single Cell Dungeon
$ Input: [[-5]]
Output: 6
💡 Note: The knight faces a -5 damage in the only room. He needs at least 6 initial health to survive: 6 + (-5) = 1 HP remaining.

Constraints

  • 1 ≤ m, n ≤ 200
  • -1000 ≤ dungeon[i][j] ≤ 1000
  • The knight can only move right or down
  • Health must remain ≥ 1 at all times

Visualization

Tap to expand
🗡️ STARTNeed: 7 HPFinal Answer!👸 GOALNeed: 1 HPStart planning here!Work Backwards!-4Need: 5+3Need: 2The Strategy:1. Start at princess location2. Calculate backwards cell by cell3. Find minimum path at each step4. Top-left = minimum initial healthPossible moves
Understanding the Visualization
1
Start at the Destination
Begin planning from the princess's cell - what's the minimum health needed to survive that final encounter?
2
Plan the Final Approach
Work backwards through the last row and column, where the knight has limited movement options
3
Map the Optimal Strategy
For each remaining cell, calculate minimum health by considering both possible next moves
4
Determine Starting Strength
The top-left cell reveals the exact initial health needed for a successful rescue!
Key Takeaway
🎯 Key Insight: By working backwards from the destination, we can determine the exact minimum health needed at each position, leading to an optimal O(m×n) solution that guarantees the knight's successful rescue mission!
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
73.9K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen