높이 가로 세로를 입력받고 3차원 배열에 데이터를 넣다가 1(익은 토마토) 가 들어오면
해당 토마토를 큐에 넣어준다.
입력이 끝나면 너비우선탐색으로 토마토를 익히고 날짜를 더해주면서 진행
만약 익힌토마토를 만나면 날짜를 더하지 않고 바로 덜익은 토마토를 찾으러 간다
토마토 익히기를 끝내고 덜익은 토마토가 있으면 -1
if(res < temp.count) res= temp.count; 에서 구한 최대 날짜를 출력한다
원래 for문을 사용하여 익은토마토를 찾아 큐에 넣어줬는데 이렇게 구현하면
10 1 1
1000000001
같은 예제에는 8이 출력된다 (4가 출력되어야 한다)
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class B7569 {
static int M,N,H;
static int[][][] box;
static boolean[][][] visited;
static int[][] D = {{-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1}}; // 위 아래 상하좌우
static int res=0;
static Queue<tomato> queue = new LinkedList<>();
static class tomato{
int h,r,c,count;
tomato(int high, int row, int col, int move){
h=high;
r=row;
c=col;
count=move;
}
}
private static void move() {
while(!queue.isEmpty()){
tomato temp = queue.remove();
if(res < temp.count) res= temp.count;
for(int i=0; i<6; i++){
int nh = temp.h + D[i][0];
int nr = temp.r + D[i][1];
int nc = temp.c + D[i][2];
if(nh<0 || nh>=H || nr<0 || nr>=N || nc<0 || nc>=M) continue;
if(visited[nh][nr][nc]) continue;
if(box[nh][nr][nc]==-1) continue;
visited[nh][nr][nc]=true;
if(box[nh][nr][nc]==0) {
box[nh][nr][nc]=1;
queue.add(new tomato(nh,nr,nc, temp.count+1));
}
if(box[nh][nr][nc]==1) {
queue.add(new tomato(nh,nr,nc, temp.count));
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
M = sc.nextInt();
N = sc.nextInt();
H = sc.nextInt();
box = new int[H][N][M];
visited = new boolean[H][N][M];
for(int h=0; h<H; h++){
for(int n=0; n<N; n++){
for(int m=0; m<M; m++){
box[h][n][m] = sc.nextInt();
if(box[h][n][m]==1){
visited[h][n][m] = true;
queue.add(new tomato(h,n,m,0));
}
}
}
}
move();
for(int h=0; h<H; h++){
for(int n=0; n<N; n++){
for(int m=0; m<M; m++){
if (box[h][n][m] == 0) {
res = -1;
break;
}
}
}
}
System.out.println(res);
}
}
'연습문제 > JAVA' 카테고리의 다른 글
5014-스타트링크 (0) | 2022.08.10 |
---|---|
14503-로봇청소기 (0) | 2022.08.10 |
11724-연결 요소의 개수 (0) | 2022.08.09 |
11724-연결 요소의 개수 (오답) (0) | 2022.08.09 |
2468-안전영역 (0) | 2022.08.08 |