You are given a grid of non-negative integers. Starting from the top-left cell, you want to reach the bottom-right cell, moving only right or down by one cell at a time.
The cost of a path is the sum of the values of every cell it visits, including both the start and end cells. Find the minimum possible path cost.
Line 1: two integers rows and cols.
The next rows lines: each contains cols non-negative integers, the grid in row-major order.
A single integer: the minimum sum of cell values over all right/down paths from the top-left cell to the bottom-right cell.
3x3 toll grid
Input
3 3 1 3 1 1 5 1 4 2 1
Expected
7
Explanation
The cheapest route runs 1->3->1 across the top row then 1->1 down the right edge, summing to 1+3+1+1+1 = 7, which is minimal.
2x3 grid
Input
2 3 1 2 5 3 2 1
Expected
6
Explanation
Going right, down, right: 1+2+2+1 = 6, which is cheaper than any other route, so the answer is 6.
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 →