A sled descends a glacier laid out as a grid of R rows and C columns. Each cell holds a non-negative traversal cost added when the sled enters that cell (the starting top-left cell is always entered). From cell (r, c) the sled may move to (r, c+1) (right), (r+1, c) (down), or (r+1, c+1) (diagonally down-right), as long as the destination stays inside the grid. It begins at the top-left cell and must reach the bottom-right cell.
Determine the minimum total cost over all such routes.
Line 1: two integers R and C.
Next R lines: each contains C non-negative integers, the costs of that row.
A single integer: the minimum total cost of a right/down/diagonal route from the top-left cell to the bottom-right cell.
Example 1
Input
2 2 1 9 9 1
Expected
2
Explanation
The diagonal move goes straight from the top-left 1 to the bottom-right 1, giving 1+1 = 2 and skipping both 9s.
Example 2
Input
1 3 2 3 4
Expected
9
Explanation
A single row allows only rightward moves, so every cell is entered: 2+3+4 = 9.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →