#K70422. Minimum Path Sum Puzzle

    ID: 33305 Type: Default 1000ms 256MiB

Minimum Path Sum Puzzle

Minimum Path Sum Puzzle

You are given a grid of size \(n \times m\) where each cell contains an integer cost. Your task is to find the path from the top-left corner to the bottom-right corner such that the sum of the values of the visited cells is minimized. You can move in four directions: up, down, left, and right.

Formally, if \(grid_{i,j}\) represents the cost at cell \((i, j)\), find a path \(P\) from \((0,0)\) to \((n-1, m-1)\) that minimizes:

\(\min_{P} \sum_{(i,j) \in P} grid_{i,j}\)

Note: The path cost includes the cost of the starting cell and the destination cell.

inputFormat

The input is read from stdin and is formatted as follows:

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

outputFormat

Output to stdout a single integer that is the minimum cost to reach the bottom-right corner from the top-left corner.

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