All problems

Problem 191

Minimum Path Sum

Medium · 20 pts · Matrix, Dynamic Programming

Problem

You are given a grid of R rows and C columns of non-negative numbers. Find a path from the top-left cell to the bottom-right cell, moving only right or down, such that the sum of the numbers on the path (including both corners) is as small as possible. Print that sum. The cheapest way to reach a cell is its own value plus the cheaper of the cell above it and the cell to its left. Fill the grid row by row with this rule.

Input

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

Output

Print the minimum path sum.

Constraints

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

Example input

3 3
1 3 1
1 5 1
4 2 1

Example output

7

Explanation

In the grid 1 3 1 / 1 5 1 / 4 2 1, the path 1 → 3 → 1 → 1 → 1 (right, right, down, down) has sum 7. Every other path passes through 5 or 4 and costs more, so the answer is 7.

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

Previous: Unique Paths with Obstacles Next: Word Break