#C3768. Minimal Path Cost in a Grid

    ID: 47231 Type: Default 1000ms 256MiB

Minimal Path Cost in a Grid

Minimal Path Cost in a Grid

You are given an n x m grid where each cell contains a non-negative integer representing the travel cost. Your task is to determine the minimum cost required to travel from the top-left corner (cell (0,0)) to the bottom-right corner (cell (n-1, m-1)). You may only move either right or down.

The cost of a path is the sum of the costs of all the cells visited along that path. The problem can be solved using dynamic programming with the following recurrence relation:

$$dp[i][j] = \min(dp[i-1][j],\,dp[i][j-1]) + grid[i][j]$$

with appropriate boundary conditions for the first row and first column.

inputFormat

The first line contains two integers, \(n\) and \(m\), which represent the number of rows and columns of the grid respectively. The next \(n\) lines each contain \(m\) space-separated integers denoting the cost values of the grid cells.

Example:

3 3
1 2 3
4 5 6
7 8 9

outputFormat

Output a single integer representing the minimum cost to travel from the top-left to the bottom-right corner of the grid.

## sample
3 3
1 2 3
4 5 6
7 8 9
21

</p>