1
+ package week3 ;
2
+
3
+ import java .io .*;
4
+ import java .util .*;
5
+
6
+ public class Main {
7
+
8
+ public static int N , M ;
9
+ public static int [][] shark ;
10
+
11
+ public static void main (String [] args ) throws IOException {
12
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
13
+ String [] input = br .readLine ().split (" " );
14
+ N = Integer .parseInt (input [0 ]);
15
+ M = Integer .parseInt (input [1 ]);
16
+ shark = new int [N ][M ];
17
+ for (int i =0 ; i <N ; i ++) {
18
+ StringTokenizer st = new StringTokenizer (br .readLine ());
19
+ for (int j =0 ; j <M ; j ++) {
20
+ shark [i ][j ] = Integer .parseInt (st .nextToken ());
21
+ }
22
+ }
23
+ int max = Integer .MIN_VALUE ;
24
+ for (int i =0 ; i <N ; i ++) {
25
+ for (int j =0 ; j <M ; j ++) {
26
+ if (shark [i ][j ] == 0 ) {
27
+ max = Math .max (max , getSafeDistance (i , j ));
28
+ }
29
+ }
30
+ }
31
+ System .out .println (max );
32
+ }
33
+
34
+ public static int getSafeDistance (int h , int w ) {
35
+ int [] dh = {-1 , -1 , -1 , 0 , 0 , 1 , 1 , 1 };
36
+ int [] dw = {-1 , 0 , 1 , -1 , 1 , -1 , 0 , 1 };
37
+
38
+ int [][] visited = new int [N ][M ];
39
+ int min = Integer .MAX_VALUE ;
40
+ Queue <int []> q = new LinkedList <>();
41
+ q .offer (new int []{h , w });
42
+ visited [h ][w ] = 1 ;
43
+ while (!q .isEmpty ()) {
44
+ h = q .peek ()[0 ];
45
+ w = q .peek ()[1 ];
46
+ q .poll ();
47
+
48
+ for (int i =0 ; i <8 ; i ++) {
49
+ int nextH = h + dh [i ];
50
+ int nextW = w + dw [i ];
51
+ if (nextH >=0 && nextH < N && nextW >=0 && nextW < M ) {
52
+ if (visited [nextH ][nextW ] == 0 ) {
53
+ if (shark [nextH ][nextW ] == 0 ) {
54
+ visited [nextH ][nextW ] = visited [h ][w ] + 1 ;
55
+ q .offer (new int []{nextH , nextW });
56
+ }else {
57
+ min = Math .min (min , visited [h ][w ]);
58
+ }
59
+ }
60
+ }
61
+ }
62
+ }
63
+ return min ;
64
+ }
65
+ }
0 commit comments