#C8430. Shortest Path in a Maze
Shortest Path in a Maze
Shortest Path in a Maze
You are given a 2D maze represented by an m × n grid. Each cell in the grid is either open (denoted by \(0\)) or a wall (denoted by \(1\)). Your task is to determine the length of the shortest path from the start at the top-left cell \((0,0)\) to the destination at the bottom-right cell \((m-1, n-1)\).
You can move from a cell to any of its adjacent cells in the four cardinal directions (up, down, left, right). Diagonal moves are not allowed. The length of the path is determined by the number of cells visited along the route, including both the starting and the ending cells.
If either the starting cell or the destination cell is a wall, or if there is no valid path between them, output \(-1\).
Note: The maze grid \(G\) satisfies:
[ G_{i,j} = \begin{cases} 0 & \text{if the cell is open}, \ 1 & \text{if the cell is a wall}. \end{cases} ]
</p>inputFormat
The input is read from standard input (stdin) and has the following format:
- The first line contains two space-separated integers \(m\) and \(n\) representing the number of rows and columns of the maze.
- The next \(m\) lines each contain \(n\) space-separated integers (either 0 or 1) representing the maze grid.
For example:
5 5 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0
outputFormat
Output a single integer on standard output (stdout) representing the length of the shortest path from the top-left cell to the bottom-right cell. If no such path exists, output -1.
## sample5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
1 1 1 1 0
0 0 0 1 0
9