#K52542. Minimum Cost Path in a Grid
Minimum Cost Path in a Grid
Minimum Cost Path in a Grid
You are given a 2D grid of size \(n \times m\) where each cell contains a positive integer representing the cost to step into that cell. Your task is to find the minimum cost path from the top-left corner to the bottom-right corner of the grid. From a cell \((i, j)\), you are allowed to move to any of its four adjacent cells: up, down, left, or right.
The cost of a path is defined as the sum of the costs of all cells visited on that path (including both the starting and the ending cells). Formally, if the path goes through cells \((i_1, j_1), (i_2, j_2), \dots, (i_k, j_k)\), the total cost is \(\sum_{t=1}^{k} cost(i_t, j_t)\).
Your solution must read the input from stdin
and output the result to stdout
.
inputFormat
The first line contains two integers \(n\) and \(m\) denoting the number of rows and columns in the grid, respectively. \(n\) lines follow, each containing \(m\) space-separated integers representing the grid.
Constraints: \(1 \leq n, m \leq 100\); each cell's cost is a positive integer.
outputFormat
Output a single integer which is the minimum cost to reach from the top-left to the bottom-right corner of the grid.
## sample3 3
1 3 1
1 5 1
4 2 1
7
</p>