Dungeon Game solution explained
Dungeon Game asks for the smallest starting health that lets a knight walk from the top-left room of a grid to the bottom-right room, moving only right or down, when each room adds or removes health and the knight dies the moment health reaches 0. Work backwards from the last room: the health needed on entering a room is the larger of 1 and the cheaper of the two next rooms' requirements minus this room's value. That fills the grid in O(rows × cols) time with one row of extra space, and the top-left value is the answer.
By Evin JohnPublished 9 min read
What is being asked
A grid of integers describes rooms. A negative number drains that much health, a positive number restores it, and 0 does nothing. A knight starts in the top-left room and must reach the bottom-right room, stepping only right or down. The knight's health, which starts at some positive integer, must stay at 1 or more after every room, including the first and last ones. Return the smallest starting health that makes the trip possible along some path.
| Grid (rows top to bottom) | Answer | Why |
|---|---|---|
| [-3, 4], [-6, -1] | 4 | Right then down: 4 - 3 = 1, then 5, then 4. Going down first needs 11. |
| [-7] | 8 | One room that takes 7; you need 1 left. |
| [5] | 1 | Health can never start below 1, even before a potion. |
| [1, 0, -2], [-3, 0, 0], [5, 0, -5] | 3 | Down, down, right, right picks up the 5 before the final -5. |
Why it trips people up
It looks like the minimum path sum problem, and the first instinct is a forward DP from the top-left. Interviewers ask it because that instinct fails, and they want to see whether you can explain why and find the direction that works. They also check the clamp: health can never be allowed to go to 0 or below in the middle, so a large potion near the end does not rescue a path that dies earlier.
Ground truth: check every path
For a single path the answer is simple: track the running total of room values, note its lowest point, and the start must be large enough that the start plus that low point is still at least 1. Trying every path and keeping the smallest requirement is correct, but a grid with r rows and c columns has C(r + c - 2, r - 1) paths, which explodes quickly.
def min_health_brute(dungeon):
rows, cols = len(dungeon), len(dungeon[0])
best = float('inf')
def walk(r, c, total, lowest):
nonlocal best
total += dungeon[r][c]
lowest = min(lowest, total) # the worst running total on this path so far
if r == rows - 1 and c == cols - 1:
best = min(best, max(1, 1 - lowest))
return
if r + 1 < rows:
walk(r + 1, c, total, lowest)
if c + 1 < cols:
walk(r, c + 1, total, lowest)
walk(0, 0, 0, 0)
return bestWhy a forward DP breaks
A forward pass would like to keep, for every room, the best way to arrive there. But there are two things to care about on arrival: how much starting health the route needed so far, and how much it has gained or lost in total. They pull in different directions. In the last grid of the table, two routes reach the room left of the bottom-right corner. One went right first and has needed only 1 so far, with a running total of 1. The other went down through the -3 and needed 3, but it collected the 5 and has a running total of 3. A forward pass that keeps the smaller requirement keeps the first route, and after the final -5 it reports 5. The route it threw away needs only 3.
Going backwards removes the conflict. If you know the health required on entering each room after this one, the health required on entering this one depends on nothing that happened before. The future fully decides the present, which is exactly what a DP needs.
The backward recurrence
Let need[r][c] be the smallest health you can walk into room (r, c) with and still finish alive. In the last room you must leave with at least 1, so need = max(1, 1 - value). In any other room you go on to whichever neighbour, below or right, asks for less; call that after. Entering with h leaves you with h + value, which must be at least after and at least 1. So need[r][c] = max(1, after - value). Fill from the bottom-right corner, right to left and bottom to top, and read need[0][0].
def calculate_minimum_hp(dungeon):
rows, cols = len(dungeon), len(dungeon[0])
need = [float('inf')] * (cols + 1) # need[c]: health required when entering column c of the row below
need[cols - 1] = 1 # stand-in for "after the last room you must still have 1"
for r in range(rows - 1, -1, -1):
for c in range(cols - 1, -1, -1):
after = min(need[c], need[c + 1]) # the easier of the two rooms you can go to next
need[c] = max(1, after - dungeon[r][c])
return need[0]The extra slot at the end of the row is a guard. Setting need[cols - 1] to 1 before the first pass makes the bottom-right room use the same formula as every other room: it looks at a "room below" whose requirement is 1 and a guard on the right that is infinite. After that, the guard column stays infinite, so rooms on the right edge only look down.
On [-3, 4], [-6, -1] the last room needs 1 - (-1) = 2. The room left of it needs 2 + 6 = 8. The room above it needs 2 - 4 = -2, clamped to 1: the potion covers everything after it, but you still have to be alive to drink it. The first room picks the cheaper next room, 1, and needs 1 + 3 = 4.
#include <algorithm>
#include <climits>
#include <vector>
using namespace std;
int calculateMinimumHP(const vector<vector<int>>& dungeon) {
int rows = dungeon.size(), cols = dungeon[0].size();
vector<long long> need(cols + 1, LLONG_MAX); // one row of answers, plus a guard column
need[cols - 1] = 1;
for (int r = rows - 1; r >= 0; --r) {
for (int c = cols - 1; c >= 0; --c) {
long long after = min(need[c], need[c + 1]); // never LLONG_MAX: one side is real
need[c] = max(1LL, after - dungeon[r][c]);
}
}
return static_cast<int>(need[0]);
}Another route: binary search on the start
If the backward idea does not come to you, there is a fallback worth knowing. Fix a starting health h. Now a forward pass is fine, because only one thing matters: the most health you can still have on leaving each room, with dead routes marked as impossible. If the knight survives with h, it survives with any larger start, so the smallest working h can be found by binary search between 1 and 1 plus the sum of all drains.
def survives(dungeon, start):
rows, cols = len(dungeon), len(dungeon[0])
dead = float('-inf')
best = [[dead] * cols for _ in range(rows)] # most health you can have after room (r, c)
for r in range(rows):
for c in range(cols):
if r == 0 and c == 0:
came = start
else:
came = max(best[r - 1][c] if r else dead, best[r][c - 1] if c else dead)
if came > 0 and came + dungeon[r][c] > 0:
best[r][c] = came + dungeon[r][c]
return best[-1][-1] > 0
def calculate_minimum_hp_search(dungeon):
lo, hi = 1, 1 + sum(-min(0, v) for row in dungeon for v in row) # hi always survives
while lo < hi:
mid = (lo + hi) // 2
if survives(dungeon, mid):
hi = mid
else:
lo = mid + 1
return loIt is slower by a log factor and longer to write, so present it as a second option or a way out if you are stuck, then mention that the backward DP removes the search.
Costs side by side
| Approach | Time | Extra space |
|---|---|---|
| Every path | O(C(R + C - 2, R - 1) · (R + C)) | O(R + C) recursion |
| Binary search plus forward check | O(R · C · log S) | O(R · C), or O(C) with care |
| Backward DP | O(R · C) | O(C) |
Cases to run before you say done
- One room with a positive value: the answer is 1, not 0 or negative.
- One room with a negative value v: the answer is 1 - v.
- A big potion after a deadly room on the only path: the potion must not cancel the earlier drain.
- A single row or a single column, where the guard logic carries all the work.
- A grid where the safest-looking first step is the wrong one.
Frequent slips
- Running the DP forward with one value per cell and getting answers that are too high on some grids.
- Dropping the max with 1, which lets potions pay for damage taken before them.
- Answering with the lowest total along the best path without adding 1, an off-by-one that the [-7] case catches.
- Filling the bottom row and right column with special cases and mixing up which neighbour exists.
- In C++, subtracting a room value from INT_MAX used as infinity, which can overflow.
How it sounds in the room
Fictional example
- Candidate
- If I go forward, each cell has two things I care about, the start health the route needed and how much it has gained. Keeping only one of them can throw away the better route.
- Candidate
- Backwards there's only one: the health I need when I walk into a room. It's the cheaper of the next two rooms' needs, minus this room's value, and never below 1.
- Interviewer
- Why never below 1?
- Candidate
- Because a potion later on can't help if I'm already dead when I get there. I still have to walk in alive. The answer is the value for the top-left room.
Related practice
Minimum Falling Path Sum is the forward-friendly grid DP to compare against. The binary search on a starting value is the same move used in Split Array Largest Sum and Capacity to Ship Packages Within D Days, and on a grid in Swim in Rising Water. Delete and Earn is a lighter DP to warm up with.
Using Natively while you practise
The hard part of this problem is the argument for going backwards, which is worth saying out loud more than once. When you practise on a Mac or Windows machine, Natively can read the dungeon problem from a screenshot and show an approach and code in its overlay, so you can compare its direction and clamp with yours. Run a spoken mock round and the saved transcript lets you check whether your explanation of the forward failure actually made sense. Read about Natively's AI interview assistant.
Questions people ask
How do you solve Dungeon Game?
Work backwards from the bottom-right room. The health needed on entering a room is the larger of 1 and the smaller of the next rooms' needs minus this room's value. The answer is the value for the top-left room.
Why does Dungeon Game need a backward DP?
Going forward, each cell would need to remember two things, how much starting health the route needed and how much it has gained, and keeping only one can discard the best route. Going backward, one number per room is enough.
What is the time complexity of Dungeon Game?
O(rows × cols) time. Extra space can be one row of O(cols) values.
Can Dungeon Game be solved with binary search?
Yes. For a fixed starting health a forward pass that keeps the most health per cell checks survival, and survival is monotonic in the start, so binary search finds the smallest start at an extra log factor.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
