#C13334. Shortest Path in a Binary Grid
Shortest Path in a Binary Grid
Shortest Path in a Binary Grid
You are given a 2D grid consisting of 0s and 1s, where 0 represents an open cell and 1 represents an obstacle. Your task is to compute the length of the shortest path from the top-left corner (0-indexed) to the bottom-right corner using a graph search algorithm.
You may move in the four cardinal directions (up, down, left, right). If there exists a path, output the number of cells traversed including both the start and the end cell. Otherwise, output \(-1\) if no such path exists.
Note: Although the problem description initially mentions depth-first search (DFS), an optimal solution typically involves breadth-first search (BFS) to guarantee the shortest path.
inputFormat
The input is given via standard input (stdin) and has the following format:
n m row1 row2 ... rown
Here, n
and m
denote the number of rows and columns respectively. Each of the next n
lines contains m
integers (either 0 or 1) separated by spaces, representing the grid.
outputFormat
Output a single integer on standard output (stdout) indicating the length of the shortest path from the top-left to the bottom-right corner. If no such path exists, output -1
.
3 3
0 0 0
0 0 0
0 0 0
5