Sub topic 14
Working Backward from the Goal
This chapter assumes you have read the earlier chapters on minimum-cost paths and on fill order. You should be comfortable with dp[i][j] recurrences, padded tables, and the one-row trick. Everything so far has filled the table from the start cell toward the goal. Some problems will not let you do that. The Dungeon Game is the standard example, and it shows when the fill direction has to be reversed and why.
The Problem
A knight starts at the top-left cell of an m x n dungeon and must reach the princess at the bottom-right cell. He moves only right or down. Each cell holds an integer. A negative value is damage, and a positive value is a healing potion. If his health drops to 0 or below at any moment, he dies, and that includes the start and goal cells.
Find the minimum starting health that lets him reach the goal alive.
| Row | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | -2 | -3 | 3 |
| row 1 | -5 | -10 | 1 |
| row 2 | 10 | 30 | -5 |
The answer for this grid is 7. One route that works is right, right, down, down. Starting with 7 health, he passes through health 5, 2, 5, 6, and ends at 1.
Why the Forward Direction Fails
Try the forward approach first: let dp[i][j] be the minimum starting health needed to reach (i, j) alive. To compute it you have to combine the two incoming paths, and one number per path does not hold enough information.
Two facts matter for a path that arrives at a cell:
- Requirement: the starting health the path needs, set by its lowest point so far.
- Surplus: how much health the knight has left when he arrives.
Suppose two paths reach cell X:
- Path A needs starting health 1 and arrives with 1 health.
- Path B needs starting health 3 and arrives with 10 health, because it took an early hit and then found a big potion.
Which path is better depends on what comes after X:
| Next cell after X | Start needed via A | Start needed via B | Better path |
|---|---|---|---|
| 0 | 1 | 3 | A |
| -8 | 9 | 3 | B |
A forward table that stores only the requirement keeps A and loses B. A table that stores only the surplus makes the opposite mistake in the other case. The best choice at X depends on the future, so the forward subproblem lacks optimal substructure. You could store a Pareto set of (requirement, surplus) pairs per cell, but that is much more expensive.
The Backward State
Define the state as a question about the future:
dp[i][j] = the minimum health the knight must have on entering cell (i, j) to reach the goal alive from there.
This state has optimal substructure. From (i, j) the knight moves to (i+1, j) or (i, j+1) and takes whichever needs less health. Before moving he must have at least min(dp[i+1][j], dp[i][j+1]) health. The cell itself changes his health by dungeon[i][j], so on entry he needs:
need = min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j]
dp[i][j] = max(1, need)The max(1, ...) clamp is the key step. A large potion can make need zero or negative, but the knight still has to be alive when he steps in. Health below 1 is never a valid entry value.
Each cell depends on the cell below it and the cell to its right. Those cells must be computed first, so the fill runs from the bottom-right corner toward the top-left.
Boundaries and Sentinels
Padding works here as it did in the forward problems, only on the opposite sides. Add an extra row below the grid and an extra column to its right, filled with infinity. Infinity means "you cannot exit this way", so min never picks it.
The goal cell needs special handling. After the knight reaches the princess he only needs to be alive, which means 1 health. Set the two padding cells next to the goal, dp[m][n-1] and dp[m-1][n], to 1. The general recurrence then handles the goal cell like any other: max(1, 1 - dungeon[m-1][n-1]).
def calculate_minimum_hp(dungeon):
m, n = len(dungeon), len(dungeon[0])
INF = float('inf')
dp = [[INF] * (n + 1) for _ in range(m + 1)]
dp[m][n - 1] = dp[m - 1][n] = 1
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
need = min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]
dp[i][j] = max(1, need)
return dp[0][0]
print(calculate_minimum_hp([[-2, -3, 3], [-5, -10, 1], [10, 30, -5]])) # 7Here is the filled table for the example, padding not shown:
| Row | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | 7 | 5 | 2 |
| row 1 | 6 | 11 | 5 |
| row 2 | 1 | 1 | 6 |
Look at dp[2][1]. The cell holds +30, so need = 6 - 30 = -24, and the clamp raises it to 1. Without the clamp, that -24 would flow up to dp[2][0] and dp[1][1] and claim the knight can enter with negative health.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Clamping only the final answer | Values that are too small, sometimes negative, inside the table and in the answer | Apply `max(1, ...)` at every cell |
| Setting only one sentinel next to the goal | Works for some shapes, but a 1 x n or m x 1 grid reads infinity | Set both `dp[m][n-1]` and `dp[m-1][n]` to 1, or special-case the goal |
| Filling top-down by habit | Reads infinity or stale values | Loop `i` and `j` from `m-1` and `n-1` down to 0 |
| Using 0 as the "alive" threshold | Off by one | The knight needs health at least 1, so the floor is 1 |
| Treating `dp[i][j]` as health after the cell | The recurrence subtracts at the wrong time | Define the state clearly as health on entry |
Shrinking to One Row
The rolling-array trick from the earlier chapter still applies, mirrored. When dp[j] is about to be overwritten it holds the value from the row below, and dp[j+1] already holds the new value to the right.
def calculate_minimum_hp_1d(dungeon):
m, n = len(dungeon), len(dungeon[0])
INF = float('inf')
dp = [INF] * (n + 1)
dp[n - 1] = 1
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
dp[j] = max(1, min(dp[j], dp[j + 1]) - dungeon[i][j])
return dp[0]
print(calculate_minimum_hp_1d([[-2, -3, 3], [-5, -10, 1], [10, 30, -5]])) # 7dp[n] stays infinity as the right-hand sentinel. Before the first row is processed, dp[n-1] = 1 plays the role of the "below the goal" sentinel. Time is O(mn) and extra space is O(n).
An Alternative: Binary Search on the Answer
Fixing the starting health changes the problem. With a known start h, more health is always better, so a forward DP that keeps the maximum health on arrival at each cell is valid. It only counts paths that never dropped below 1. Feasibility is monotonic: if h works, so does h + 1. That means you can binary search for the smallest h that works.
def can_survive(dungeon, h):
m, n = len(dungeon), len(dungeon[0])
NEG = float('-inf')
best = [[NEG] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
prev = h
else:
top = best[i - 1][j] if i > 0 else NEG
left = best[i][j - 1] if j > 0 else NEG
prev = max(top, left)
cur = prev + dungeon[i][j]
best[i][j] = cur if cur >= 1 else NEG
return best[m - 1][n - 1] >= 1
def min_hp_binary_search(dungeon):
lo = 1
hi = 1 + sum(-x for row in dungeon for x in row if x < 0)
while lo < hi:
mid = (lo + hi) // 2
if can_survive(dungeon, mid):
hi = mid
else:
lo = mid + 1
return lo
print(min_hp_binary_search([[-2, -3, 3], [-5, -10, 1], [10, 30, -5]])) # 7The upper bound hi always works because it covers every possible hit on the grid. The cost is O(mn log V), where V is that total damage.
| Approach | Time | Extra space | When to prefer it |
|---|---|---|---|
| Backward DP | O(mn) | O(n) with one row | Default: simplest and fastest |
| Binary search + forward feasibility | O(mn log V) | O(mn) or O(n) | When the backward recurrence is hard to derive but feasibility for a fixed start is easy to check |
Recognizing Backward Problems
Consider reversing the fill direction when:
- The constraint must hold at every step along the path, as with "health stays positive", and not just at the end.
- The quantity you want, such as starting health or initial budget, is decided at the start but limited by what happens later.
- The forward state needs two numbers that trade off against each other.
Counting paths and minimum path sum give the same answer in either direction, because addition and min do not care which end you start from. The Dungeon Game differs because of the clamp: max(1, ...) sets a floor at every step, and a floor cuts a path into stages. Cutting from the goal end means each subproblem is a single number.
Exercise
For the 1 x 1 dungeon [[5]] and the 1 x 1 dungeon [[-5]], what does calculateminimumhp return, and which line of the code produces each answer?
Show answer
For [[5]] it returns 1. Both sentinels are 1, so need = 1 - 5 = -4, and max(1, -4) = 1. The clamp produces the answer, because the knight must still enter the cell with at least 1 health. For [[-5]] it returns 6, since need = 1 - (-5) = 6 and the clamp leaves it unchanged.
Exercise
A student fills the dungeon table with dp[i][j] = min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j] and returns max(1, dp[0][0]). Give a small grid where this returns the wrong answer, and explain why.
Show answer
Use [[-5], [30], [-1]], a single column. The correct values from the bottom are: row 2 gives max(1, 1+1) = 2, row 1 gives max(1, 2-30) = 1, and row 0 gives max(1, 1+5) = 6. The answer is 6. Without per-cell clamping, row 1 becomes -28 and row 0 becomes -28+5 = -23, so the student returns max(1, -23) = 1. That is wrong because starting with 1 health and taking 5 damage kills the knight. The potion's surplus leaked backward through the table and cancelled damage that happens before the potion is reached.
Exercise
Why is it valid to keep only the maximum health per cell in the forward feasibility check, when the forward minimum-requirement DP was invalid?
Show answer
In the feasibility check the starting health is fixed, so every path that is still alive has met the same requirement. The only thing left that differs between paths is the current health, and more health is never worse for any future. One number per cell is enough. In the requirement DP the starting health is unknown, and paths differ in two ways (requirement and surplus) that trade off against each other.