Information

Author(s) François Aubry
Deadline Καμία προθεσμία
Submission limit No limitation

Συνδεθείτε

Graphs - Problem: Fire!


Fire!

Adapted from: UVa 11624

Joe works in a maze. Unfortunately, portions of the maze have caught on fire, and the owner of the maze neglected to create a fire escape plan.

Your task is to help Joe escape the maze.

Given Joe’s location in the maze and which squares of the maze are on fire, you must determine whether Joe can exit the maze before the fire reaches him, and how fast he can do it.

Joe and the fire each move one square per minute, vertically or horizontally (not diagonally). The fire spreads all four directions from each square that is on fire. Joe may exit the maze from any square that borders the edge of the maze. Neither Joe nor the fire may enter a square that is occupied by a wall.

Example

The following image illustrates the first sample test case. Joe is represented in blue, the fire in red and the walls in gray. Joe can escape in 5 minutes as shown in the animation.

graphs-prob-fire/anim.gif

Input

The first line of the input contains two integers giving the number of rows \(n\) and columns \(m\) in the maze, respectively.

Then follow \(n\) lines each with a string on length \(m\) giving the rows of the mazer. Each string is defined of the alphabet '#', '.', 'J' and 'F' each of the characters having the following meaning:

  • '#': a wall
  • '.': an empty space
  • 'J': the initial position of Joe
  • 'F': a position that is on fire at the start

There will be exactly one 'J' in the maze.

Constraints

  • \(1 \leq n, m \leq 1000\).

Output

For each test case, output a single line containing IMPOSSIBLE if Joe cannot exit the maze before the fire reaches him, or an integer giving the earliest time Joe can safely exit the maze, in minutes.

Note that it still takes Joe one minute to go out of the maze once he is already at the border (see the first sample test case, the answer is 5 not 4).

Sample Test Cases

Sample input 1

Sample output 1

Sample input 2

Sample output 2

Sample input 3

Sample output 3


Max file size: 1.0 MiB
Allowed extensions: .java, .cpp, .py