#K80197. Shortest Path in a Maze

    ID: 35477 Type: Default 1000ms 256MiB

Shortest Path in a Maze

Shortest Path in a Maze

You are given a maze represented as a 2D grid. Each cell in the maze can be either empty (denoted by 0) or a wall (denoted by 1). Your task is to find the shortest path from the top-left corner (0-indexed) to the bottom-right corner of the maze.

You can only move in four directions: up, down, left, or right. If the starting cell or ending cell is a wall, or if there is no valid path, output -1.

The length of the path is defined as the number of cells traveled including the source and destination cells. In mathematical terms, if the path is of length \(L\), you should output \(L\). Otherwise, if no path exists, output \(-1\).

inputFormat

The input is given via standard input (stdin) and has the following format:

R C
row1
row2
...
rowR

Where:

  • R and C are two space-separated integers representing the number of rows and the number of columns of the maze respectively.
  • Each of the next R lines contains C space-separated integers (either 0 or 1) representing the maze.

outputFormat

Output the minimum number of steps required to reach the bottom-right corner from the top-left corner. If it is not possible, output -1. The output should be written to standard output (stdout).

## sample
2 2
0 1
0 0
3