이전 문제와 같은데 입력만 한번 더 받은 문제였다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | package baekjun; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; class Coor{ int x; int y; int z; Coor(int x, int y, int z){ this.x = x; this.y = y; this.z = z; } } public class baekjun7569 { static int n; static int m; static int l; static int[][][] matrix; static int[][][] tomato; static Queue<Coor> q = new LinkedList<Coor>(); 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}; private static void BFS() { // TODO Auto-generated method stub while(!q.isEmpty()) { Coor c = q.poll(); int x = c.x; int y = c.y; int z = c.z; for(int k=0; k<dx.length; k++) { int nx = x + dx[k]; int ny = y + dy[k]; int nz = z + dz[k]; if(nx >= 0 && ny >= 0 && nz>=0 && nx<n && ny<m && nz<l) { if(matrix[nx][ny][nz] == 0 && tomato[nx][ny][nz]==-1) { matrix[nx][ny][nz] = 1; tomato[nx][ny][nz] = tomato[x][y][z] + 1; q.add(new Coor(nx,ny,nz)); } } } } } private static void lastCheck() { // TODO Auto-generated method stub int rs = 1; for(int k=0; k<l; k++) { for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(matrix[i][j][k] == 0) { System.out.println("-1"); return; } if(tomato[i][j][k] > rs) { rs = tomato[i][j][k]; } } } } System.out.println(rs); } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); boolean check = false; n = sc.nextInt(); //행 m = sc.nextInt(); //열 l = sc.nextInt(); matrix = new int [n][m][l]; tomato = new int[n][m][l]; for(int k=0; k<l; k++) { for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { matrix[i][j][k] = sc.nextInt(); tomato[i][j][k] = -1; if(matrix[i][j][k]==1) { tomato[i][j][k] = 0; q.add(new Coor(i,j,k)); } if(matrix[i][j][k]==0 && check) { check = true; } } } } if(check) System.out.println(0); else { BFS(); lastCheck(); } } } | cs |
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 2667번 단지번호붙이기 Java (DFS, BFS) (0) | 2020.02.16 |
---|---|
[백준] 7576번 토마토 (0) | 2018.08.21 |
[백준] 1260 DFS와 BFS (0) | 2018.08.20 |
백준 2747, 2748 피보나치 수 (0) | 2018.08.06 |
백준 10866번 덱(Deque) (0) | 2018.07.30 |
댓글