#C2115. Minimum Steps in a Grid
Minimum Steps in a Grid
Minimum Steps in a Grid
Given an m × n grid where each cell is either open (0) or blocked (1), your task is to compute the minimum number of steps required to move from the top-left cell (0, 0) to the bottom-right cell (m-1, n-1) avoiding obstacles. You may move one step at a time in any of the four cardinal directions (up, down, left, right).
If the destination is not reachable, return -1
.
The movement can be formulated as finding the shortest path in a grid, where each valid move has a cost of 1. In mathematical terms, if you denote the number of steps by \(s\), find the minimum \(s\) such that:
\[ (0,0) \rightarrow (m-1, n-1) \text{ using valid moves}, \]Note that both the starting cell and the destination cell must be open.
inputFormat
The input is given via standard input (stdin) and consists of:
- A line containing two integers
m
andn
, the number of rows and columns respectively. - Followed by
m
lines, each containingn
space-separated integers (either 0 or 1) representing the grid.
outputFormat
Output a single integer to standard output (stdout): the minimum number of steps from the start to the destination. If there is no valid path, output -1
.
3 3
0 0 0
1 0 1
0 0 0
4