Music streaming app~35 min2s · 256 MBtarget O(R × C) time, O(C) spaceclassic twin: lc-174dp
A game inside a streaming app is played on a grid of rooms. Entering a room changes the player's health by a whole number: a trap lowers it and a potion raises it. The player starts in the top left room and must reach the bottom right room, moving one room right or one room down each time.
Health must never drop below 1, or the player is out. Your team lead asks: "What is the least health the player needs at the start to be safe on some route?"
Write least_start_health(dungeon).
dungeon[r][c] is the change in health on entering room (r, c). It is negative for a trap, positive for a potion, and the first and last rooms count.(0, 0) and finishes in the last room. Each move goes one room right or one room down.Input: dungeon = [[-3, 5, -4], [-6, -9, 8], [2, -7, -2]]
Output: 4Add up totals from the start and you cannot tell what health is needed: the lowest point of a route matters, not its end. So work from the exit backwards. Let need[r][c] be the least health the player must have on entering room (r, c) to reach the exit alive.
In the last room, need = max(1, 1 - change). Elsewhere the player needs what the easier next room needs, minus the change here, and never less than 1: need[r][c] = max(1, min(need[r + 1][c], need[r][c + 1]) - dungeon[r][c]).
| Row | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| 2 | 2: max(1, 10 - (2)) = 8 | -7: max(1, 3 - (-7)) = 10 | -2: max(1, 1 - (-2)) = 3 |
| 1 | -6: max(1, 8 - (-6)) = 14 | -9: max(1, 1 - (-9)) = 10 | 8: max(1, 3 - (8)) = 1 |
| 0 | -3: max(1, 1 - (-3)) = 4 | 5: max(1, 5 - (5)) = 1 | -4: max(1, 1 - (-4)) = 5 |
The first room needs 4, so the player starts with at least 4.
Input: dungeon = [[5]]
Output: 1One room with a potion. Health must still be at least 1 at the start, so the answer is 1.
Input: dungeon = [[-4]]
Output: 5One room with a trap of 4. The player needs 5, so that 5 - 4 = 1 is left.
1 ≤ rows ≤ 200 and 1 ≤ cols ≤ 200, and every row has the same length.-1,000 ≤ dungeon[r][c] ≤ 1,000A grid of 200 by 200 rooms has 40,000 rooms and about 10 to the power 118 routes. A table with one entry for each room takes about 40,000 steps. A route that looks best from the start may be unsafe, so the table works backwards from the exit.