
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static int size_x, size_y, size_z;
static int[][][] board;
static boolean[][][] visited;
static Queue<int[]> queue;
static int unripe;
// 상 하 좌 우 아래 위
static int[] dx = {0, 0, -1, 1, 0, 0};
static int[] dy = {-1, 1, 0, 0, 0, 0};
static int[] dz = {0, 0, 0, 0, -1, 1};
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
size_x = Integer.parseInt(st.nextToken());
size_y = Integer.parseInt(st.nextToken());
size_z = Integer.parseInt(st.nextToken());
board = new int[size_z][size_y][size_x];
visited = new boolean[size_z][size_y][size_x];
queue = new LinkedList<>();
for (int z = 0; z < size_z; z++) {
for (int y = 0; y < size_y; y++) {
st = new StringTokenizer(br.readLine());
for (int x = 0; x < size_x; x++) {
board[z][y][x] = Integer.parseInt(st.nextToken());
if (board[z][y][x] == 0) {
unripe++; // unripe tomato++
} else if (board[z][y][x] == 1) {
queue.add(new int[]{z, y, x}); // add tomato
visited[z][y][x] = true;
}
}
}
}
br.close();
//solve
int day = 0;
while (!queue.isEmpty()) {
if (unripe == 0) {
break;
}
int loopCount = queue.size();
while (loopCount != 0) {
if (unripe == 0) {
break;
}
int[] current = queue.poll();
int z = current[0];
int y = current[1];
int x = current[2];
for (int i = 0; i < 6; i++) {
int addZ = z + dz[i];
int addY = y + dy[i];
int addX = x + dx[i];
if (isValidPos(addZ, addY, addX) &&
!visited[addZ][addY][addX] &&
board[addZ][addY][addX] == 0) {
queue.add(new int[]{addZ, addY, addX});
visited[addZ][addY][addX] = true;
unripe--;
}
}
loopCount--;
}
day++;
}
bw.write(Integer.toString((unripe == 0) ? day : -1));
bw.close();
}
static boolean isValidPos(int z, int y, int x) {
return 0 <= z && z < size_z &&
0 <= y && y < size_y &&
0 <= x && x < size_x;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 7662번: 이중 우선순위 큐 (0) | 2025.04.07 |
|---|---|
| [JAVA-자바] 10026번: 적록색약 (0) | 2025.04.04 |
| [JAVA-자바] 5430번: AC (0) | 2025.04.02 |
| [JAVA-자바] 5525번: IOIOI (0) | 2025.04.01 |
| [JAVA-자바] 11403번: 경로 찾기 (0) | 2025.04.01 |