Hide

Problem F
Fire

You are trapped in a building consisting of open spaces and walls. Some places are on fire and you have to run for the exit. Will you make it?

At each second, the fire will spread to all open spaces directly connected to the North, South, East or West side of it. Fortunately, walls will never catch fire and will keep the fire inside the building, so as soon as you are out of the building you will be safe. To run to any of the four open spaces adjacent to you takes you exactly one second. You cannot run through a wall or into an open space that is on fire or is just catching fire, but you can run out of an open space at the same moment it catches fire.

Given a map of the building, decide how fast you can exit the building.

Input

On the first line one positive number: the number of test cases, at most 100. After that per test case:

  • one line with two space-separated integers $w$ and $h$ $(1\le w, h \le 1\, 000)$: the width and height of the map of the building, respectively.

  • $h$ lines with $w$ characters each: the map of the building, consisting of

    • .’: a room,

    • #’: a wall,

    • @’: your starting location,

    • *’: fire.

    There will be exactly one ‘@’ in the map.

Output

Per test case:

  • one line with a single integer which is the minimal number of seconds that you need to exit the building or the string “IMPOSSIBLE” when this is not possible.

Sample Input 1 Sample Output 1
5
4 3
####
#*@.
####
7 6
###.###
#*#.#*#
#.....#
#.....#
#..@..#
#######
7 4
###.###
#....*#
#@....#
.######
5 5
.....
.***.
.*@*.
.***.
.....
3 3
###
#@#
###
2
5
IMPOSSIBLE
IMPOSSIBLE
IMPOSSIBLE

Please log in to submit a solution to this problem

Log in