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
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!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code