All problems

Problem 450

Dungeon Game

Hard · 30 pts · Matrix, Dynamic Programming

Problem

A knight starts in the top-left room of an R x C dungeon and must reach the princess in the bottom-right room, moving only right or down. Each room changes the knight's health by its value: negative values are demons that hurt him, positive values are potions that heal him. If his health ever drops to 0 or below, he dies. Find the minimum initial health (at least 1) that lets him reach the princess. Work backwards from the bottom-right: need[i][j] is the health required when entering room (i, j).

Input

First line: R and C. Next R lines: C integers each.

Output

Print the minimum initial health.

Constraints

1 <= R, C <= 200; -1000 <= value <= 1000

Example input

3 3
-2 -3 3
-5 -10 1
10 30 -5

Example output

7

Explanation

In the dungeon -2 -3 3 / -5 -10 1 / 10 30 -5, the path right, right, down, down loses 2 and 3, gains 3 and 1, and loses 5. Starting with 7 health, the knight never drops below 1.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Cherry Pickup with Two Robots Next: Number of Longest Increasing Subsequences