#K79327. Minimum Steps to Exit in a Maze

    ID: 35284 Type: Default 1000ms 256MiB

Minimum Steps to Exit in a Maze

Minimum Steps to Exit in a Maze

You are given a maze represented as a grid of n rows and m columns. The cell in the top-left corner represents the entrance and the cell in the bottom-right corner represents the exit. Each grid cell contains either a 1 or a 0, where 1 means the cell is accessible and 0 means it is blocked.

Your task is to determine the minimum number of steps required to reach the exit from the entrance, moving only in four directions: up, down, left, and right. If it is not possible to reach the exit, output -1.

The number of steps is counted by the number of cells visited (including both the entrance and the exit). The movement is allowed only if the cell is within the boundaries and is not blocked.

Formally, if we denote the grid as \(A\) where \(A_{ij} = 1\) indicates an open cell and \(A_{ij} = 0\) indicates a blocked cell, and if \(S\) is the starting cell \((1,1)\) and \(E\) is the ending cell \((n,m)\), find the minimum number of steps required to travel from \(S\) to \(E\). Use \(\LaTeX\) for any formulas.

inputFormat

The input begins with a line containing two integers \(n\) and \(m\) representing the number of rows and columns respectively. This is followed by \(n\) lines, each containing \(m\) space-separated integers. Each integer is either 0 or 1, where 1 represents an accessible cell and 0 represents a blocked cell.

Example:

3 3
1 0 0
1 1 0
0 1 1

outputFormat

Output a single integer representing the minimum number of steps required to reach the exit. If there is no valid path, output -1.

## sample
3 3
1 0 0
1 1 0
0 1 1
5

</p>