문제 링크 : https://www.acmicpc.net/problem/7569
백준 7576 토마토 문제를 풀고 난 후에 시도한 문제라서 쉬울 거라 생각하고 문제를 접근했다.
7576 토마토는 2차원 문제라면 7569 토마토는 3차원 문제였다.
알고 있는 유형의 문제라서 그런지 너무 쉽게 생각하여 입력 방식에 대해 잘못 구현했다.
첫 시도는 틀렸습니다를 받았다. 문제를 다시 정독한 후 입력 방식을 바꾸고 문제를 해결했다.
구현에 대해서는 어렵지 않았지만 문제를 파악하는데 실수가 있었다.
알고 있는 유형의 문제라도 빠른 해결을 위해 꼼꼼히 읽어보자!!
아래와 같이 구현 소스를 공유합니다.
public class 토마토 {
public static class Node {
int x, y, h, s;
Node(int x, int y, int h, int s) {
this.x = x;
this.y = y;
this.h = h;
this.s = s;
}
}
public static int X, Y, H, cnt;
public static int[][][] arr;
public static boolean[][][] visit;
public static Queue<Node> que = new LinkedList<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
Y = Integer.parseInt(str[0]);
X = Integer.parseInt(str[1]);
H = Integer.parseInt(str[2]);
arr = new int[X][Y][H];
visit = new boolean[X][Y][H];
boolean isSuccessed = true;
for (int f = 0; f < H; f++) {
for (int i = 0; i < X; i++) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for (int j = 0; j < Y; j++) {
int v = Integer.parseInt(st.nextToken());
if(v == 0) isSuccessed = false;
if(v == 1) {
que.add(new Node(i, j, f, 0));
visit[i][j][f] = true;
}
arr[i][j][f] = v;
}
}
}
if(isSuccessed) {
System.out.println("0");
}else {
bfs();
boolean isCompleted = true;
for (int f = 0; f < H; f++) {
for (int i = 0; i < X; i++) {
for (int j = 0; j < Y; j++) {
int v = arr[i][j][f];
if(v == 0) isCompleted = false;
}
}
}
if(isCompleted) {
System.out.println(cnt-1);
}else {
System.out.println("-1");
}
}
}
public static void bfs() {
int[] dx = {0, -1, 0, 1, 0, 0};
int[] dy = {-1, 0, 1, 0, 0, 0};
int[] dh = {0, 0, 0, 0, -1, 1};
while(!que.isEmpty()) {
int size = que.size();
cnt++;
for (int i = 0; i < size; i++) {
Node node = que.poll();
for (int j = 0; j < 6; j++) {
int xx = node.x + dx[j], yy = node.y + dy[j], hh = node.h + dh[j];
if(xx < X && yy < Y && hh < H && xx >= 0 && yy >= 0 && hh >= 0) {
if(!visit[xx][yy][hh] && arr[xx][yy][hh] == 0) {
visit[xx][yy][hh] = true;
arr[xx][yy][hh] = node.s + 1;
que.add(new Node(xx, yy, hh, node.s + 1));
}
}
}
}
}
}
}
'알고리즘 > 문제풀이 - 백준온라인저지' 카테고리의 다른 글
[BOJ] 배열 돌리기 1 16926.JAVA (0) | 2021.04.12 |
---|---|
[BOJ] 달팽이 1913.JAVA (0) | 2021.04.11 |
[BOJ] 전화번호 목록 5052.JAVA (0) | 2021.03.29 |
[BOJ] 소년점프 16469.JAVA (0) | 2021.03.29 |
[이것이 코딩테스트다] 게임 개발 (JAVA) (0) | 2021.03.18 |