#K34102. Minimum Moves to Reach Destination in a Grid

    ID: 25235 Type: Default 1000ms 256MiB

Minimum Moves to Reach Destination in a Grid

Minimum Moves to Reach Destination in a Grid

You are given a grid with n rows and m columns. Each cell in the grid is either open (0) or blocked (1). A robot is situated at the top-left corner of the grid (cell (0, 0)) and needs to reach the bottom-right corner (cell (n-1, m-1)). The robot can move in four directions: up, down, left, and right. Your task is to determine the minimum number of moves required for the robot to reach the destination. If the destination is unreachable or the start/end positions are blocked, output -1.

The problem can be modeled using breadth-first search (BFS) to find the shortest path from the start to the destination in an unweighted grid. The number of moves is the length of the path from the start to the destination. Formally, if a path exists, output its length; otherwise, output \( -1 \).

inputFormat

The first line contains two integers n and m (number of rows and columns respectively).

Each of the next n lines contains m space-separated integers, each representing a cell in the grid (0 for open and 1 for blocked).

outputFormat

Output a single integer, which is the minimum number of moves required for the robot to reach the destination (bottom-right corner). If it is impossible to reach the destination, output -1.

## sample
3 3
0 0 0
1 1 0
0 0 0
4