#C845. Shortest Path in an Obstructed Grid
Shortest Path in an Obstructed Grid
Shortest Path in an Obstructed Grid
You are given a grid of size $n \times m$, where each cell is either open (represented by 0
) or blocked (represented by 1
). Your task is to find the length of the shortest path from the top-left cell $(0,0)$ to the bottom-right cell $(n-1, m-1)$.
The movement is restricted to horizontal and vertical directions only (up, down, left, and right). If no valid path exists, output -1
.
Note: The grid indices satisfy $0 \le i < n$ and $0 \le j < m$, and the starting cell as well as the ending cell must be open (i.e. have a value of 0
).
inputFormat
The first line contains two space-separated integers n
and m
, representing the number of rows and columns, respectively. The next n
lines each contain m
space-separated integers (each integer is either 0
or 1
), representing the grid.
outputFormat
Output a single integer: the length of the shortest path from the top-left corner to the bottom-right corner. If no such path exists, output -1
.
2 2
0 1
1 0
-1