#K46547. Minimum Moves in a Grid
Minimum Moves in a Grid
Minimum Moves in a Grid
You are given a grid with N rows and M columns. Each cell in the grid is either empty (denoted by 0) or blocked (denoted by 1). Your task is to find the minimum number of moves required to move from the top-left cell (0, 0) to the bottom-right cell (N-1, M-1).
You can move up, down, left, or right from a cell, but you cannot move diagonally. You cannot move onto a blocked cell. If it is impossible to reach the bottom-right cell, output -1.
Note: The problem uses 0-indexed cell positions.
The solution typically involves a breadth-first search (BFS) over the grid. The formula for the move count is determined by the shortest path length in an unweighted grid graph, i.e.,
\(D = d((0,0), (N-1, M-1))\)
where \(d(u,v)\) is the minimum number of moves between cell \(u\) and cell \(v\).
inputFormat
The first line of input contains two integers N and M separated by a space, representing the number of rows and columns respectively. The following N lines each contain M space-separated integers (either 0 or 1) representing the grid.
outputFormat
Output a single integer: the minimum number of moves required to reach the bottom-right cell from the top-left cell. If it is impossible to reach the destination, output -1.
## sample3 3
0 1 0
0 0 0
0 1 0
4
</p>