#C14651. Minimum Path Cost

    ID: 44324 Type: Default 1000ms 256MiB

Minimum Path Cost

Minimum Path Cost

Given a grid of non-negative integers, where each cell represents a cost, your task is to determine the minimum cost required to travel from the top-left corner to the bottom-right corner of the grid. You may move only down or right at any point in time.

If the grid is empty, the result should be 0.

The cost of a path is the sum of the costs of all visited cells (including both the starting and ending cells). Formally, if you have a grid \( grid \) with \( R \) rows and \( C \) columns, and \( dp[i][j] \) represents the minimum cost to reach cell \( (i,j) \), then the recurrence relation is:

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

with the initialization \( dp[0][0] = grid[0][0] \). In the first row and column, the path cost is cumulative.

inputFormat

The input is read from the standard input (stdin) and has the following format:

  1. The first line contains two integers \( R \) and \( C \) separated by a space, representing the number of rows and columns in the grid, respectively.
  2. Then \( R \) lines follow, each containing \( C \) integers separated by spaces. Each integer represents the cost of the corresponding cell in the grid.

If \( R = 0 \) or \( C = 0 \), the grid is considered empty and the output should be 0.

outputFormat

The output should be a single integer written to standard output (stdout) representing the minimum cost to travel from the top-left corner to the bottom-right corner of the grid.

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