#C10390. Minimum Moves in a Grid
Minimum Moves in a Grid
Minimum Moves in a Grid
You are given a rectangular grid consisting of cells with values 0 and 1. A cell with value 0 represents an open cell, while a cell with value 1 represents an obstacle. A robot starts at a specified cell and must move to a destination cell. The robot may move one step at a time in the four cardinal directions (up, down, left, right) and cannot move into an obstacle cell.
Your task is to determine the minimum number of moves required for the robot to travel from the starting cell to the destination cell. If the destination cannot be reached, output -1.
Input Format:
- The first line contains two integers M and N which denote the number of rows and columns in the grid, respectively.
- The next M lines each contain N integers (0 or 1) representing the grid.
- The following line contains two integers representing the starting cell coordinates (row and column).
- The last line contains two integers representing the destination cell coordinates (row and column).
Output Format: Output a single integer denoting the minimum number of moves required to reach the destination, or -1 if it is impossible.
The solution should use a breadth-first search (BFS) algorithm for optimal performance. The answer should be formatted using LaTeX for any formulas. For example, the number of moves required is given by \(d\), where \(d\) is the minimum distance from the start to the destination.
inputFormat
The input is read from standard input (stdin) and has the following format:
M N row1_element1 row1_element2 ... row1_elementN ... rowM_element1 rowM_element2 ... rowM_elementN start_row start_col destination_row destination_col
Where:
- M and N are the dimensions of the grid.
- The next M lines contain N integers each (each integer is 0 or 1).
- The start position and destination position are given as row and column indices (0-indexed).
outputFormat
Output a single integer to standard output (stdout) which is the minimum number of moves required to reach the destination. If the destination is unreachable, output -1.
## sample4 4
0 0 0 1
0 1 0 0
0 0 0 0
1 0 1 0
0 0
2 2
4