[java 백준]실버 1/ 7576번 토마토

[java 백준]실버 1/ 7576번 토마토

import java.util.LinkedList;

import java.util.Queue;

import java.util. Scanner ;

public class Main {

public static int [][][] arr;

public static int day = 0 ;

public static int n;

public static int m;

public static int h;

public static int [] dirX = { - 1 , 0 , 1 , 0 , 0 , 0 }; // 상하좌우위아래

public static int [] dirY = { 0 , 1 , 0 , - 1 , 0 , 0 }; // 상하좌우위아래

public static int [] dirZ = { 0 , 0 , 0 , 0 , - 1 , 1 };

// 새로 익은 토마토에 대해서만 탐색

static class Tomato {

int x;

int y;

int z;

int day;

public Tomato( int z, int x, int y) { // 초기화

this .x = x;

this .y = y;

this .z = z;

}

}

static Queue < Tomato > queue = new LinkedList < Tomato > ();

public static void bfs() {

while ( ! queue.isEmpty()) {

Tomato tomato = queue.poll();

int x = tomato.x;

int y = tomato.y;

int z = tomato.z;

for ( int i1 = 0 ; i1 < 6 ; i1 + + ) {

int X = x + dirX[i1];

int Y = y + dirY[i1];

int Z = z + dirZ[i1];

if (X > = 0 & & X < n & & Y > = 0 & & Y < m & & Z > = 0 & & Z < h) {

if (arr[Z][X][Y] = = 0 ) {

queue. add ( new Tomato(Z, X, Y));

arr[Z][X][Y] = arr[z][x][y] + 1 ;

}

}

}

}

}

public static void main( String [] args) {

Scanner sc = new Scanner ( System . in );

m = sc.nextInt();

n = sc.nextInt();

h = sc.nextInt();

arr = new int [h][n][m];

for ( int i = 0 ; i < h; i + + ) {

for ( int j = 0 ; j < n; j + + ) {

for ( int k = 0 ; k < m; k + + ) {

arr[i][j][k] = sc.nextInt();

}

}

}

for ( int i = 0 ; i < h; i + + ) {

for ( int j = 0 ; j < n; j + + ) {

for ( int k = 0 ; k < m; k + + ) {

if (arr[i][j][k] = = 1 ) {

queue. add ( new Tomato(i, j, k));

}

}

}

}

bfs();

int result = 0 ;

boolean search = false ;

for ( int i = 0 ; i < h; i + + ) {

for ( int j = 0 ; j < n; j + + ) {

for ( int k = 0 ; k < m; k + + ) {

if (arr[i][j][k] = = 0 ) {

search = true ;

}

result = Math.max(result, arr[i][j][k]);

}

}

}

if (search) {

System . out . println ( - 1 );

} else {

if (result = = 1 ) {

System . out . println ( 0 );

} else {

System . out . println (result - 1 );

}

}

}

}

from http://we1cometomeanings.tistory.com/166 by ccl(A) rewrite - 2021-10-03 19:01:53