링크텍스트

import java.io.*;
import java.util.*;
public class Main{
static int m,n;
static int [] dx ={0,0,-1,1};
static int [] dy ={1,-1,0,0};
static int [][] arr;
static Queue<int []> q = new LinkedList<>();
static int count = 0;
static int day = 0;
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
m = Integer.parseInt(st.nextToken());
n = Integer.parseInt(st.nextToken());
arr = new int[n][m];
for(int i=0;i<n;i++){
st = new StringTokenizer(br.readLine());
for(int j=0;j<m;j++){
arr[i][j] = Integer.parseInt(st.nextToken());
if(arr[i][j]==1){
q.add(new int[] {i,j});
}else if(arr[i][j]==0){
count++;
}
}
}
bfs();
}
public static void bfs(){
while(count>0 && !q.isEmpty()){
int size = q.size();
for(int i=0;i<size;i++){
int [] point = q.poll();
int cx = point[0];
int cy = point[1];
for(int j=0;j<4;j++){
int xx = cx + dx[j];
int yy = cy + dy[j];
if(xx>=0 && xx<n && yy>=0 && yy<m && arr[xx][yy]==0){
q.add(new int[] {xx,yy});
arr[xx][yy]= 1;
count--;
}
}
}
day++;
}
if(count==0){
System.out.println(day);
}else
System.out.println(-1);
}
}
