728x90
문제
접근 방식
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토
www.acmicpc.net
위 문제에 위, 아래층 탐색이 추가된 문제로
기존에는 2차원 배열의 토마토 상자의 앞뒤양옆의
익지 않은 토마토들을 하루마다 익어가게 만들었다면
이번에는 앞뒤양옆 + 상하를 하루마다 익어가게 해주면 된다.
문제의 푸는 방법은 같지만 2차원 배열에서 3차원 배열로 바뀐만큼
기존 방식에 약간의 변화를 줘야 한다.
private static class XYZ {
private int z;
private int x;
private int y;
private int day;
public XYZ(int z, int x, int y, int day) {
this.z = z;
this.x = x;
this.y = y;
this.day = day;
}
}
일단 기존에는 x, y축만 사용했다면 z축을 추가해주고
날짜를 기록하기 위해 day 필드를 추가해줬다.
이제 이를 이용해서 하루마다 앞뒤양옆상하 방향의
익지 않은 사과들을 BFS를 통해 익혀주면 된다.
풀이
public class Main {
private static int[] dx = {1, -1, 0, 0, 0, 0};
private static int[] dy = {0, 0, 1, -1, 0, 0};
private static int[] dz = {0, 0, 0, 0, 1, -1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] mnh = br.readLine().split(" ");
int m = Integer.parseInt(mnh[0]);
int n = Integer.parseInt(mnh[1]);
int h = Integer.parseInt(mnh[2]);
int[][][] box = new int[h][n][m];
boolean[][][] isVisited = new boolean[h][n][m];
Queue<XYZ> queue = new ArrayDeque<>();
int unripe = 0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < n; j++) {
String[] input = br.readLine().split(" ");
for (int k = 0; k < m; k++) {
int tomato = Integer.parseInt(input[k]);
box[i][j][k] = tomato;
if (tomato == 0) unripe++;
if (tomato == 1) {
queue.offer(new XYZ(i, j, k, 0));
isVisited[i][j][k] = true;
}
}
}
}
if (unripe == 0) {
System.out.println(0);
return;
}
while (!queue.isEmpty()) {
XYZ cur = queue.poll();
for (int i = 0; i < 6; i++) {
int x = cur.x + dx[i];
int y = cur.y + dy[i];
int z = cur.z + dz[i];
if (x < 0 || x >= n || y < 0 || y >= m || z < 0 || z >= h) continue;
if (isVisited[z][x][y] || box[z][x][y] == -1) continue;
unripe--;
if (unripe == 0) {
System.out.println(cur.day + 1);
return;
}
isVisited[z][x][y] = true;
queue.offer(new XYZ(z, x, y, cur.day + 1));
}
}
System.out.println(-1);
}
private static class XYZ {
private int z;
private int x;
private int y;
private int day;
public XYZ(int z, int x, int y, int day) {
this.z = z;
this.x = x;
this.y = y;
this.day = day;
}
}
}
'Java > Algorithms' 카테고리의 다른 글
[백준] 5427번 : 불 (0) | 2023.11.07 |
---|---|
[백준] 7562번 : 나이트의 이동 (0) | 2023.11.07 |
[백준] 1941번 : 소문난 칠공주 (0) | 2023.11.07 |
[백준] 16987번 : 계란으로 계란치기 (0) | 2023.11.01 |
[백준] 6603번 : 로또 (0) | 2023.11.01 |