#C953. Minimum Cost Path in a Grid

    ID: 53633 Type: Default 1000ms 256MiB

Minimum Cost Path in a Grid

Minimum Cost Path in a Grid

You are given a square grid of size n × n where each cell contains an integer representing a height. Starting from the top-left cell (grid[0][0]), your task is to determine the minimum cost required to reach the bottom-right cell (grid[n-1][n-1]). You can only move either right or down at any step.

The cost of moving from a cell (i, j) to an adjacent cell (k, l) is defined as the absolute difference between their heights, i.e.,

Cost=grid[i][j]grid[k][l].\text{Cost} = |grid[i][j] - grid[k][l]|.

Your goal is to find a path from the top-left to the bottom-right cell such that the sum of the costs along the path is minimized.

Example:

Input:
2
1 2
4 3

Output: 2

Explanation: The path is 1 -> 2 -> 3 and the cost is |1-2| + |2-3| = 1 + 1 = 2

</p>

inputFormat

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

  • The first line contains a single integer n denoting the size of the grid.
  • The next n lines each contain n space-separated integers representing the grid's rows.

For example:

2
1 2
4 3

outputFormat

Output a single integer to standard output (stdout) representing the minimum cost to travel from the top-left to the bottom-right cell.

For example, for the sample input above, the output should be:

2
## sample
2
1 2
4 3
2