#K85592. Minimum Cost Path in a Grid
Minimum Cost Path in a Grid
Minimum Cost Path in a Grid
You are given an (m \times n) grid containing non-negative integers. Your task is to find the minimum cost path from the top-left cell (i.e. cell ( (0,0) )) to the bottom-right cell (i.e. cell ( (m-1, n-1) )). At any point, you are only allowed to move either right or down. The cost of a path is defined as the sum of the values in the grid cells visited along the path. Formally, if a path is represented as ((0,0) \to (i_1,j_1) \to \cdots \to (m-1, n-1)), then the path cost is given by:
[ Cost = \sum_{(i,j) \in \text{path}} grid[i][j] ]
Your goal is to compute and output this minimum cost.
Example:
For the grid:
1 3 1
1 5 1
4 2 1
The minimum cost path is: 1 (\to) 3 (\to) 1 (\to) 1 (\to) 1, which has a total cost of 7.
inputFormat
Input Format:
The first line contains two integers (m) and (n), denoting the number of rows and columns, respectively. This is followed by (m) lines, each containing (n) space-separated non-negative integers representing the grid values.
outputFormat
Output Format:
Output a single integer which is the minimum cost to reach the bottom-right corner from the top-left corner along a valid path.## sample
3 3
1 3 1
1 5 1
4 2 1
7