#K75932. Minimum Moves in a Grid
Minimum Moves in a Grid
Minimum Moves in a Grid
You are given an n x m grid of integers where each cell represents a height. You need to determine the minimum number of moves required for a vehicle to travel from the top-left corner of the grid (cell (0,0)) to the bottom-right corner (cell (n-1, m-1)). The vehicle can only move in four directions: up, down, left, or right.
A move from cell (x,y) to a neighboring cell (x',y') is allowed if and only if:
$$grid[x'][y'] \le grid[x][y] + 1$$
If it is impossible to reach the destination under these conditions, output -1
. Otherwise, output the minimum number of moves.
inputFormat
The input is read from standard input (stdin) and has the following format:
- The first line contains two integers n and m separated by a space, representing the number of rows and columns of the grid.
- The next n lines each contain m integers separated by spaces, representing the grid.
outputFormat
Output a single integer to standard output (stdout): the minimum number of moves required to reach the bottom-right cell. If it is impossible to reach the destination, output -1
.
3 4
0 1 2 3
1 2 3 4
2 3 4 5
5