Dungeon Game

HardDynamic Programming2d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A knight enters a dungeon laid out as an m x n grid at the top-left cell and must reach the princess in the bottom-right cell, moving only right or down. Each cell holds an integer: a negative value is damage the knight takes on entering it, a positive value is health restored, and 0 does nothing. The first and last cells apply their values too. If the knight's health ever drops to 0 or below, he dies immediately. Return the smallest positive integer starting health that lets the knight reach the princess alive along some path.

Examples

Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
Output: 7
Going right, right, down, down visits -2, -3, 3, 1, -5. Starting with 7, health goes 5, 2, 5, 6, 1 and never hits 0.
Input: dungeon = [[0]]
Output: 1
The knight needs at least 1 health just to be alive.

Constraints

  • 1 <= m, n <= 200
  • -1000 <= dungeon[i][j] <= 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 2d dp problems