1
+ package BOJ ;
2
+
3
+ import java .io .BufferedReader ;
4
+ import java .io .IOException ;
5
+ import java .io .InputStreamReader ;
6
+ import java .util .*;
7
+
8
+ public class BOJ_5427 {
9
+ private static int w , h , step ;
10
+ private static boolean flag ;
11
+ private static char [][] graph ;
12
+ private static int [] dx = {-1 , 1 , 0 , 0 };
13
+ private static int [] dy = {0 , 0 , -1 , 1 };
14
+ private static Queue <Node > queue , fire_queue ;
15
+
16
+ private static void logic () {
17
+ while (!fire_queue .isEmpty () || !queue .isEmpty ()) {
18
+ int fqlen = fire_queue .size ();
19
+ for (int s = 0 ; s < fqlen ; s ++) {
20
+ Node f = fire_queue .poll ();
21
+
22
+ for (int d = 0 ; d < 4 ; d ++) {
23
+ int nx = f .x + dx [d ];
24
+ int ny = f .y + dy [d ];
25
+
26
+ if (0 <= nx && nx < h && 0 <= ny && ny < w ) {
27
+ if (graph [nx ][ny ] == '.' || graph [nx ][ny ] == '@' ) {
28
+ graph [nx ][ny ] = '*' ;
29
+ fire_queue .add (new Node (nx , ny ));
30
+ }
31
+ }
32
+ }
33
+ }
34
+
35
+ int qlen = queue .size ();
36
+ if (qlen > 0 ) {
37
+ step ++;
38
+
39
+ for (int s = 0 ; s < qlen ; s ++) {
40
+ Node n = queue .poll ();
41
+
42
+ for (int d = 0 ; d < 4 ; d ++) {
43
+ int nx = n .x + dx [d ];
44
+ int ny = n .y + dy [d ];
45
+
46
+ if (nx < 0 || nx >= h || ny < 0 || ny >= w ) {
47
+ flag = true ;
48
+ return ;
49
+ }
50
+
51
+ if (graph [nx ][ny ] == '.' ) {
52
+ graph [nx ][ny ] = '@' ;
53
+ queue .add (new Node (nx , ny ));
54
+ }
55
+ }
56
+ }
57
+ } else {
58
+ return ;
59
+ }
60
+ }
61
+ }
62
+
63
+
64
+ public static void main (String []args ) throws IOException {
65
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
66
+ int T = Integer .parseInt (br .readLine ());
67
+
68
+ for (int tc = 1 ; tc <= T ; tc ++) {
69
+ StringTokenizer st = new StringTokenizer (br .readLine ());
70
+ w = Integer .parseInt (st .nextToken ());
71
+ h = Integer .parseInt (st .nextToken ());
72
+
73
+ graph = new char [h ][w ];
74
+ flag = false ;
75
+ step = 0 ;
76
+
77
+ for (int i = 0 ; i < h ; i ++) {
78
+ graph [i ] = br .readLine ().toCharArray ();
79
+ }
80
+
81
+ queue = new ArrayDeque <>();
82
+ fire_queue = new ArrayDeque <>();
83
+
84
+
85
+ for (int i = 0 ; i < h ; i ++) {
86
+ for (int j = 0 ; j < w ; j ++) {
87
+ if (graph [i ][j ] == '@' ) {
88
+ queue .add (new Node (i , j ));
89
+ }
90
+ if (graph [i ][j ] == '*' ) {
91
+ fire_queue .add (new Node (i , j ));
92
+ }
93
+ }
94
+ }
95
+ logic ();
96
+ System .out .println (flag == true ? step : "IMPOSSIBLE" );
97
+ }
98
+ br .close ();
99
+ }
100
+
101
+ private static class Node {
102
+ int x , y ;
103
+
104
+ public Node (int x , int y ) {
105
+ this .x = x ;
106
+ this .y = y ;
107
+ }
108
+ }
109
+ }
0 commit comments