#C10107. Minimum Steps in a Grid Maze

    ID: 39276 Type: Default 1000ms 256MiB

Minimum Steps in a Grid Maze

Minimum Steps in a Grid Maze

You are given a 2D grid maze with (N) rows and (M) columns. Each cell of the maze is either open (denoted by '0') or a wall (denoted by '1'). You start at the top-left corner (cell (0,0)) and need to reach the bottom-right corner (cell (N-1, M-1)). You can move in four directions: up, down, left, or right. Your task is to determine the minimum number of steps required to travel from the entrance to the exit. If the exit is unreachable, output (-1).

The problem can be solved efficiently using the Breadth-First Search (BFS) algorithm, which has a time complexity of (O(N \times M)).

inputFormat

The first line contains two space-separated integers (N) and (M), representing the number of rows and columns of the grid respectively. The next (N) lines each contain a string of length (M) composed of characters '0' and '1', where '0' represents an open cell and '1' represents a wall.

outputFormat

Output a single integer which is the minimum number of steps from the entrance to the exit. If the destination is unreachable, output (-1).## sample

3 3
000
010
000
4