All problems

Problem 935

Nearest Exit from Entrance in Maze

Medium · 20 pts · Matrix, Breadth-First Search

Problem

A maze has empty cells '.' and walls '+'. You stand at the empty ENTRANCE cell and can move up, down, left or right through empty cells. An exit is an empty cell on the border of the maze; the entrance itself does not count as an exit. Find the fewest steps to reach the nearest exit, or print -1 if there is none. A breadth-first search from the entrance finds it level by level.

Input

The first line contains R, C, and the entrance row and column (0-based). Each of the next R lines is a row of the maze.

Output

Print the number of steps to the nearest exit, or -1.

Constraints

1 <= R, C <= 100; the entrance is an empty cell

Example input

3 4 1 2
++.+
...+
+++.

Example output

1

Explanation

In ++.+ / ...+ / +++. with the entrance at (1, 2), moving up once reaches (0, 2), an empty border cell. So the answer is 1.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: As Far from Land as Possible Next: Jump Game IV