#K55617. Maze Shortest Path
Maze Shortest Path
Maze Shortest Path
You are given a two-dimensional grid maze consisting of n rows and m columns. Each cell is either open or blocked. The value 0 indicates an open cell and 1 indicates a blocked cell. You are also given the starting position and the target position in the grid (using 0-indexed coordinates).
Your task is to find the shortest path from the start to the target position while moving only in the four cardinal directions: up, down, left, and right.
If there is no valid path, output -1.
The problem can be formalized as finding the minimum number of steps required to go from the start to the target. Mathematically, if the distance is denoted by d, then you should output:
\[ d = \begin{cases} \text{minimum steps from start to target,} & \text{if a path exists}, \\ -1, & \text{otherwise.} \end{cases} \]Note: The start or target cell might be blocked in some cases.
inputFormat
The input is read from standard input (stdin) and has the following format:
n m row1 row2 ... rown sx sy ex ey
Here:
- n and m are the number of rows and columns of the grid.
- Each of the next n lines contains m integers (0 or 1) representing the grid.
- sx and sy represent the starting position (row and column).
- ex and ey represent the target position (row and column).
outputFormat
Print a single integer to standard output (stdout): the minimum number of steps needed to go from the start to the target position. If there is no path, print -1.
## sample5 5
0 0 1 0 0
0 1 0 0 1
0 1 0 1 0
0 0 0 0 0
1 1 0 1 0
0 0
3 4
7