#K5851. Shortest Path in a Grid

    ID: 30658 Type: Default 1000ms 256MiB

Shortest Path in a Grid

Shortest Path in a Grid

You are given a grid of size (n \times m) where each cell is either open or blocked. An open cell is represented by a 0 and a blocked cell by a 1. Your task is to determine the shortest path from the top-left cell (0, 0) to the bottom-right cell (n-1, m-1). You may move in four directions: up, down, left, or right (no diagonal moves allowed). If a valid path exists, output the minimum number of steps required; otherwise, output (-1).

inputFormat

The input is given via stdin. The first line contains two integers (n) and (m), representing the number of rows and columns. The following (n) lines each contain (m) space-separated integers (either 0 or 1) that define the grid.

outputFormat

Output a single integer to stdout: the length of the shortest path from the top-left cell to the bottom-right cell. If no such path exists, output (-1).## sample

5 6
0 0 1 0 0 0
1 0 1 1 1 0
1 0 0 0 0 0
0 0 1 1 0 1
0 1 1 1 0 0
10