알고리즘(BOJ)/Gold
7569 - 토마토(BFS)
ch.0
2022. 12. 27. 11:39
package test;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
//백준
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int wide = sc.nextInt();
int depth = sc.nextInt();
int high = sc.nextInt();
int[][][] array = new int[high][depth][wide];
boolean[][][] visited = new boolean[high][depth][wide];
Queue<int[]> q = new LinkedList<>();
int x = 0, y = 0, z = 0, date = 0, cnt=0;
for (int k = 0; k < high; k++) {
for (int i = 0; i < depth; i++) {
for (int j = 0; j < wide; j++) {
array[k][i][j] = sc.nextInt();
if (array[k][i][j] == 1) {
x = i;
y = j;
z = k;
q.offer(new int[] { x, y, z, date });
visited[k][i][j] = true;
}
if(array[k][i][j] == 0) {
cnt++;
}
}
}
}
while (cnt>0&&!q.isEmpty()) {
int[] point = q.poll();
x = point[0];
y = point[1];
z = point[2];
date = point[3];
// System.out.println(x+","+y+" "+date);
date++;
if (array[z][x][y] == 1) {
if (x > 0 && array[z][x - 1][y] == 0 && visited[z][x - 1][y] == false) {// 상
q.offer(new int[] { x - 1, y, z, date });
array[z][x - 1][y] = 1;
visited[z][x-1][y] = true;
cnt--;
}
if (x < depth - 1 && array[z][x + 1][y] == 0 && visited[z][x + 1][y] == false) {// 하
q.offer(new int[] { x + 1, y, z, date });
array[z][x + 1][y] = 1;
visited[z][x+1][y] = true;
cnt--;
}
if (y > 0 && array[z][x][y - 1] == 0 && visited[z][x][y - 1] == false) {// 좌
q.offer(new int[] { x, y - 1, z, date });
array[z][x][y - 1] = 1;
visited[z][x][y-1] = true;
cnt--;
}
if (y < wide - 1 && array[z][x][y + 1] == 0 && visited[z][x][y + 1] == false) {// 우
q.offer(new int[] { x, y + 1, z, date });
array[z][x][y + 1] = 1;
visited[z][x][y+1] = true;
cnt--;
}
if (z>0 && array[z-1][x][y] == 0 && visited[z-1][x][y] == false) {// 아래
q.offer(new int[] { x, y, z - 1, date });
array[z-1][x][y] = 1;
visited[z-1][x][y] = true;
cnt--;
}
if (z<high-1 && array[z+1][x][y] == 0 && visited[z+1][x][y] == false) {// 위
q.offer(new int[] { x, y, z + 1, date });
array[z+1][x][y] = 1;
visited[z+1][x][y] = true;
cnt--;
}
}
// for (int i = 0; i < depth; i++) {
// for (int j = 0; j < wide; j++) {
// System.out.print(array[i][j]);
// }System.out.println();
// }System.out.println("------------"+count);
}
if (cnt==0) {
System.out.println(date);
}else {
System.out.println("-1");
}
// if(wide<2||depth<2||high<2) {
// date=1;
// }
}
}
0일경우에 cnt를 늘려주고
토마토가 익을때마가 cnt를 줄여줬다.
해당 조건이 없을때에는 반례는 찾지 못했지만 에러가 났다.
cnt가 0일경우 즉 0인 숫자가 아예없을때는 핵심로직 자체를 안타게 했다.
(기존에는 이 조건이 없어서 일단 핵심로직을 타긴 했다.)