#K59157. Minimum Steps in a Grid
Minimum Steps in a Grid
Minimum Steps in a Grid
This problem requires you to determine the minimum number of steps required to move from a starting cell to a destination cell in a grid. The grid is represented as a 2D matrix where each cell is either an open space (denoted by 0
) or an obstacle (denoted by 1
). Movement is allowed only in the four cardinal directions: up, down, left, and right.
If it is impossible to reach the destination (for example, if the starting or destination cell is an obstacle, or if there is no valid path), you should output -1
.
In a grid without obstacles, the minimum number of steps required is given by the formula: \( \text{steps}_{min} = |r_2 - r_1| + |c_2 - c_1| \), where \((r_1, c_1)\) is the starting position and \((r_2, c_2)\) is the destination.
inputFormat
The input is provided via standard input (stdin) and consists of multiple lines:
- The first line contains two space-separated integers \( R \) and \( C \) representing the number of rows and columns of the grid.
- The next \( R \) lines each contain \( C \) space-separated values, each being either
0
or1
, representing the grid. - The following line contains two space-separated integers representing the starting cell coordinates (row and column). Rows and columns are 0-indexed.
- The final line contains two space-separated integers representing the destination cell coordinates (row and column).
outputFormat
Output a single integer to standard output (stdout): the minimum number of steps required to reach the destination from the starting cell, or -1
if no valid path exists.
5 5
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 1 0 1 0
0 0 0 0 0
0 0
4 4
8