1+ import java .io .*;
2+ import java .util .*;
3+
4+ public class Main {
5+
6+ static int N ,M , arr [][], visited [][], startN , startM ;
7+ static int dx [] = {-1 ,1 ,0 ,0 };
8+ static int dy [] = {0 ,0 ,-1 ,1 };
9+ public static void main (String [] args ) throws IOException {
10+
11+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
12+
13+ StringTokenizer st = new StringTokenizer (br .readLine ());
14+ N = Integer .parseInt (st .nextToken ());
15+ M = Integer .parseInt (st .nextToken ());
16+
17+ arr = new int [N +1 ][M +1 ];
18+ visited = new int [N +1 ][M +1 ];
19+
20+ for (int i =1 ; i <=N ; i ++) {
21+ st = new StringTokenizer (br .readLine ());
22+ for (int j =1 ; j <=M ; j ++) {
23+ arr [i ][j ] = Integer .parseInt (st .nextToken ());
24+ if (arr [i ][j ]==2 ) {
25+ startN = i ;
26+ startM = j ;
27+ }
28+ }
29+ }
30+ bfs (startN , startM );
31+ for (int i =1 ; i <=N ; i ++) {
32+ for (int j =1 ; j <=M ; j ++) {
33+ if (visited [i ][j ] == 0 && arr [i ][j ]== 1 )
34+ System .out .print (-1 +" " );
35+ else
36+ System .out .print (visited [i ][j ] +" " );
37+ }
38+ System .out .println ();
39+ }
40+ }
41+
42+ static void bfs (int startN , int startM ) {
43+
44+ visited [startN ][startM ] = 0 ;
45+
46+ Queue <int []> queue = new LinkedList <>();
47+ queue .add (new int [] { startN , startM });
48+
49+ while (!queue .isEmpty ()) {
50+ int now [] = queue .poll ();
51+ int nowx = now [0 ];
52+ int nowy = now [1 ];
53+
54+ for (int i =0 ; i <4 ; i ++) {
55+ int nx = nowx + dx [i ];
56+ int ny = nowy + dy [i ];
57+
58+ if (nx >=1 && nx <=N && ny <=M && ny >=1 && arr [nx ][ny ] ==1 ) {
59+ if (visited [nx ][ny ]== 0 || visited [nx ][ny ] > visited [nowx ][nowy ]+1 ) {
60+ visited [nx ][ny ] = visited [nowx ][nowy ] +1 ;
61+ queue .add (new int [] {nx ,ny });
62+ }
63+ }
64+ }
65+ }
66+ }
67+ }
0 commit comments