#C3937. Shortest Path in a Grid

    ID: 47419 Type: Default 1000ms 256MiB

Shortest Path in a Grid

Shortest Path in a Grid

You are given a grid of size \(n \times m\) consisting of 0's and 1's. A 0 indicates an open cell and a 1 indicates a wall. Your task is to find the length of the shortest path from the top-left cell (1,1) to the bottom-right cell (n,m). You can only move in four directions: up, down, left, and right and you cannot move through a wall.

Note: If either the starting cell or the destination cell is blocked, or if no valid path exists, output \(-1\). The path length is defined as the number of cells visited along the path, including the starting and ending cells.

Constraints: \(1 \le n, m \le 100\).

inputFormat

The input is read from standard input (stdin) and has the following format:

n m
row_1
row_2
... 
row_n

Where the first line contains two integers \(n\) and \(m\), representing the number of rows and columns of the grid, respectively. Each of the next \(n\) lines contains \(m\) space-separated integers (each either 0 or 1) representing a row of the grid.

outputFormat

Output a single integer to standard output (stdout) representing the length of the shortest path from the top-left to the bottom-right. If no such path exists, output \(-1\).

## sample
4 4
0 0 1 0
1 0 0 0
1 1 0 1
0 0 0 0
7