#C370. Minimum Steps to Reach Bottom-Right

    ID: 47156 Type: Default 1000ms 256MiB

Minimum Steps to Reach Bottom-Right

Minimum Steps to Reach Bottom-Right

You are given an integer grid with M rows and N columns. Your task is to determine the minimum number of steps required to move from the top-left cell \((0,0)\) to the bottom-right cell \((M-1,N-1)\), under the following movement rules:

  • You may only move to the right or downward.
  • You may only move to a cell if its value is less than or equal to the value of your current cell.

If it is impossible to reach the destination following the above rules, output -1.

Note: A step is defined as moving from one cell to an adjacent cell following the allowed directions.

inputFormat

The first line contains two integers M and N (the number of rows and columns respectively).

This is followed by M lines, each containing N space-separated integers representing the grid’s cells.

Input is read from standard input (stdin).

outputFormat

Output a single integer: the minimum number of steps required to reach the bottom-right cell from the top-left cell following the given rules, or -1 if it is not possible.

Output is written to standard output (stdout).

## sample
3 4
10 8 8 7
9 7 6 5
8 7 5 4
5