#K64202. Minimum Steps to Exit the Maze

    ID: 31923 Type: Default 1000ms 256MiB

Minimum Steps to Exit the Maze

Minimum Steps to Exit the Maze

You are given a rectangular maze represented as an N × M grid. Each cell in the grid is either open (represented by .) or blocked (represented by /). A visitor is initially located at cell \( (S_x, S_y) \) (0-indexed). The visitor can move one cell at a time in any of the four cardinal directions (up, down, left, or right), but can only move to open cells.

The goal is to determine the minimum number of steps required for the visitor to exit the maze. A maze exit is defined as reaching any cell on the boundary of the grid (i.e. any cell where \( x=0 \), \( x=N-1 \), \( y=0 \), or \( y=M-1 \)). If the visitor starts at a boundary cell, the answer is \( 0 \). If there is no possible path to an exit, output \( -1 \).

Mathematical Formulation:

Given a grid \( G \) of size \( N\times M \) and a starting point \( (S_x, S_y) \), find the minimum \( k \) such that there exists a sequence of moves \( (x_0,y_0), (x_1,y_1),\dots,(x_k,y_k) \) with \( (x_0,y_0)=(S_x,S_y) \) and \( (x_k,y_k) \) on the boundary, and each consecutive pair of cells is adjacent (up, down, left, or right) and open (i.e. equal to .). If no such \( k \) exists, output \( -1 \>.

inputFormat

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

  • The first line contains two integers \( N \) and \( M \) separated by a space.
  • The next \( N \) lines each contain a string of length \( M \) representing a row of the grid. Each character is either . (open cell) or / (blocked cell).
  • The last line contains two integers \( S_x \) and \( S_y \) separated by a space, indicating the starting cell's coordinates.

outputFormat

Output a single integer (to standard output, stdout): the minimum number of steps required to reach any boundary cell. If it is impossible to exit the maze, output \( -1 \).

## sample
5 5
.....
././.
.....
/././
.....
2 2
2