#K42397. Shortest Path in a Grid
Shortest Path in a Grid
Shortest Path in a Grid
You are given a grid consisting of m rows and n columns. Each cell of the grid contains either 0 or 1. A value of 0 indicates that the cell is free to move into, and 1 indicates an obstacle.
Your task is to compute the shortest path from the top-left corner (cell (0,0)) to the bottom-right corner (cell (m-1, n-1)). The path length is defined as the number of cells in the path including both the starting and ending cells. You may move only in four directions: up, down, left, and right. If there is no valid path, return -1.
Note: The answer should be produced using a breadth-first search (BFS) strategy to account for grid obstacles. When counting steps, the starting cell is counted as 1.
The problem can be formulated using the following LaTeX equations:
Grid size: \(m \times n\).
Path length from \((0,0)\) to \((m-1,n-1)\): \(d\) such that the path is the shortest.
If no path exists, output \(-1\).
inputFormat
The input is read from stdin and is formatted as follows:
- The first line contains two integers,
m
andn
, separated by a space, representing the number of rows and columns respectively. - The next
m
lines containn
integers each. Each integer is either 0 or 1, representing the grid cells.
outputFormat
Output the length of the shortest path from the top-left to the bottom-right cell. If there is no valid path, output -1
. The result is printed to stdout.
3 3
0 1 0
0 1 0
0 0 0
5
</p>