Sub topic 14
Working Backward from the Goal
This chapter assumes you know the minimum-cost path recurrence, padded tables with sentinel values, and the idea that fill order must follow dependencies. Every grid so far was filled from the top-left corner toward the goal. Some problems only make sense the other way around.
The Dungeon Problem
A knight starts at the top-left cell of a grid and must reach the princess in the bottom-right cell, moving only right or down. Each cell changes his health: negative values are damage and positive values are healing. If his health ever reaches 0 or below, he dies. Find the minimum starting health that lets him survive.
Why Forward DP Breaks
A forward state such as "best health on arrival at (i, j)" mixes two goals that work against each other. One path might arrive with high current health but have dipped close to death earlier. Another might arrive weaker but have needed less health at the start. Neither path is strictly better, so no single number per cell captures the answer. You would have to track both current health and the lowest health seen so far, and the two cannot be merged.
The fix is to change what a cell remembers.
The Backward State
Let dp[i][j] be the minimum health the knight needs when entering cell (i, j) so that he can still reach the goal alive. This value depends only on the cells ahead of him, never on how he got here. The future is what matters, so the table fills from the goal back to the start.
If the knight leaves (i, j) toward the cheaper next cell, he needs min(dp[i+1][j], dp[i][j+1]) after this cell's effect. Before the effect he therefore needs that amount minus dungeon[i][j]. Health must also be at least 1 at all times:
dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j])Implementation
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]])) # 7The padding row and column hold infinity, so min never chooses a move that leaves the grid. The two cells next to the goal are set to 1. This means "after the goal cell, he only needs to be alive," and the general recurrence then handles the goal cell like any other cell.
The filled table for the example:
| row | col 0 | col 1 | col 2 |
|---|---|---|---|
| 0 | 7 | 5 | 2 |
| 1 | 6 | 11 | 5 |
| 2 | 1 | 1 | 6 |
When to Think Backward
Reverse the direction when the quantity you are optimizing depends on what happens after a cell rather than before it. Constraints that must hold at every step, such as "never drop below a threshold," are the usual sign. The cost is still O(mn) time, and the rolling-row trick from earlier chapters still cuts space to O(n). The only change is that you keep the row below instead of the row above.
Exercise
What does calculateminimumhp return for [[-3]] and for [[5]]? Explain each.
Show answer
For [[-3]] it returns 4: he must have 1 health left after taking 3 damage, so he needs 4 on entry. For [[5]] it returns 1: the requirement 1 - 5 = -4 is clamped by max(1, ...), because he must be alive on entry before the healing applies.
Exercise
In the table above, dp[2][1] is 1 even though dp[2][2] is 6. Why?
Show answer
Cell (2, 1) heals by 30. Entering it with 1 health leaves 31, which is more than the 6 needed for the goal cell. The raw requirement 6 - 30 = -24 is then clamped up to 1.