Dynamic programming · Medium
A grid records the cost of visiting each cell in a planned processing route. The route starts at the top left and finishes at the bottom right, moving only right or down. Every visited cell, including both endpoints, contributes to the total.
Return the smallest possible sum of visited cell costs for a valid right-or-down route.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ grid: integer[][] }
Fields
- grid is a rectangular matrix of signed integer costs with no blocked cells.
- The empty grid is represented by []. Non-empty rows all have the same positive length.
Output
Return value
- Return the minimum numeric cost, not a route or a number of steps. Negative costs are permitted.
- Return null for an empty grid. A single cell returns its own cost.
Constraints
- 0 <= rows <= 300; 1 <= columns <= 300 for a non-empty grid.
- -1000000 <= grid[r][c] <= 1000000. Do not mutate the grid.
Examples
Example 1
{
"grid": [
[
1,
3,
1
],
[
1,
5,
1
],
[
4,
2,
1
]
]
}Returns
7Example 2
{
"grid": [
[
-5,
2
]
]
}Returns
-3Required complexity
O(rows × columns) time and O(columns) auxiliary space