728x90
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class algo_7576_김어진 {
static int N;
static int M;
static int[][] board;
static int[] dx = {-1,0,1,0};
static int[] dy = {0,1,0,-1};
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
int answer = 0;
board = new int[N][M];
for (int i = 0; i < N; i++) {
board[i]= Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
}
Queue<tomato> q = new LinkedList<tomato>();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if(board[i][j]==1) {
q.add(new tomato(i,j,0));
}
}
}
while(!q.isEmpty()) {
tomato pos = q.poll();
int x = pos.x;
int y = pos.y;
int time = pos.time;
for (int z = 0; z < 4; z++) {
int nx = x+dx[z];
int ny = y+dy[z];
if(nx>=0 && nx < N && ny>=0 && ny <M && board[nx][ny]==0) {
board[nx][ny]=1;
q.add(new tomato(nx,ny,time+1));
answer = Math.max(answer, time+1);
}
}
}
int cnt = check();
if(cnt>0) {
System.out.println(-1);
return;
}
System.out.println(answer);
}
private static int check() {
int cnt = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if(board[i][j]==0) {
cnt++;
}
}
}
return cnt;
}
}
class tomato{
public tomato(int x, int y, int time) {
super();
this.x = x;
this.y = y;
this.time = time;
}
int x;
int y;
int time;
}
728x90
'알고리즘 > 백준' 카테고리의 다른 글
백준 1194 달이차오른다, 가자 (자바) (0) | 2021.09.29 |
---|---|
백준 2458 키 순서 (자바) (0) | 2021.09.29 |
백준 14502 연구소 (자바) (0) | 2021.09.17 |
백준 9205 맥주 마시면서 걸어가기 (자바) (0) | 2021.09.16 |
백준 말이 되고픈 원숭이 (자바) (0) | 2021.09.15 |