728x90
풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static String[][] arr = null;
public static int[] changeX = {-1, 1, 0, 0};
public static int[] changeY = {0, 0, -1, 1};
public static int day = -1;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] arrNum = br.readLine().split(" ");
arr = new String[Integer.parseInt(arrNum[1])][Integer.parseInt(arrNum[0])];
for(int i=0; i<arr.length; i++) {
arr[i] = br.readLine().split(" ");
}
roop();
System.out.println(day);
}
public static void roop() {
Queue<Node> que = new LinkedList<>();
for(int i=0; i<arr.length; i++) {
for(int j=0; j<arr[0].length; j++) {
if("1".equals(arr[i][j])) {
que.add(new Node(i, j));
}
}
}
while(!que.isEmpty()) {
int dayPlusFlay = que.size();
day++;
for(int i=0; i<dayPlusFlay; i++) {
Node getNode = que.poll();
arr[getNode.x][getNode.y] = "2";
for(int j=0; j<4; j++) {
int nextX = getNode.x + changeX[j];
int nextY = getNode.y + changeY[j];
if(nextX >= 0 && nextX < arr.length && nextY >= 0 && nextY < arr[0].length) {
if("0".equals(arr[nextX][nextY])) {
arr[nextX][nextY] = "1";
que.add(new Node(nextX, nextY));
}
}
}
}
}
for(int i=0; i<arr.length; i++) {
for(int j=0; j<arr[0].length; j++) {
if("0".equals(arr[i][j])) {
day = -1;
i = arr.length;
j = arr[0].length;
}
}
}
}
public static class Node {
int x;
int y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
}
}
'코딩 문제 > 백준' 카테고리의 다른 글
백준 - 26004번 (0) | 2024.03.10 |
---|---|
백준 - 13460번 (0) | 2023.06.18 |
백준 - 28086번 (0) | 2023.06.18 |
백준 - 16437번 (1) | 2021.03.25 |
백준 - 1987번 (0) | 2021.03.25 |