#K86872. Minimum Cost Path

    ID: 36961 Type: Default 1000ms 256MiB

Minimum Cost Path

Minimum Cost Path

You are given a grid containing non-negative integers. Your task is to find the minimum cost path from the top-left corner to the bottom-right corner of the grid. You may only move either down or right at any step.

The problem can be solved using dynamic programming. Let \( dp[i][j] \) denote the minimum cost to reach cell \( (i,j) \), then:

\( dp[i][j] = \min(dp[i-1][j],\; dp[i][j-1]) + grid[i][j] \) for \( i,j \ge 1 \).

If the grid is empty, the answer is 0.

inputFormat

The input is given through standard input (stdin) and has the following format:

  • The first line contains two integers \( N \) and \( M \) representing the number of rows and columns of the grid.
  • This is followed by \( N \) lines, each containing \( M \) integers separated by spaces representing the grid.

outputFormat

Output a single integer to standard output (stdout): the minimum cost from the top-left to the bottom-right of the grid.

## sample
3 3
1 3 1
1 5 1
4 2 1
7