#K80522. Minimum Cost Path
Minimum Cost Path
Minimum Cost Path
You are given a grid (matrix) consisting of n rows and m columns. Each cell of the grid contains a non-negative integer representing the cost required to step on that cell. Your task is to find the minimum cost to travel from the top-left cell (starting point) to the bottom-right cell (destination).
You can only move either to the right or down at any step. The total cost of a path is the sum of the costs of all cells visited along the path.
Mathematical formulation:
Let \(\text{cost}_{i,j}\) denote the cost of cell at row \(i\) and column \(j\). Define \(dp[i][j]\) as the minimum cost to reach cell \((i,j)\) from the start. Then, the recurrence relation is given by:
[ dp[i][j] = \text{cost}_{i,j} + \min\begin{cases} dp[i-1][j] & \text{if } i > 0, \ dp[i][j-1] & \text{if } j > 0 \end{cases} ]
The answer is \(dp[n-1][m-1]\).
inputFormat
The input is read from standard input (stdin) and has the following format:
- The first line contains two space-separated integers n and m, representing the number of rows and columns of the grid.
- The following n lines each contain m space-separated integers. The j-th integer on the i-th line denotes the cost of cell \((i, j)\).
outputFormat
Output the minimum cost required to travel from the top-left cell to the bottom-right cell. The result should be printed to the standard output (stdout) as a single integer.
## sample3 3
1 3 1
1 5 1
4 2 1
7
</p>