2021년 10월 23일 토요일 22시
[DFSBFS] 백준_7569_토마토DFSBFS_실버1
https://www.acmicpc.net/problem/7569
7569번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,
www.acmicpc.net
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Three {
int x;
int y;
int z;
Three(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
}
public class Main {
static int[] dx = { -1, 0, 1, 0, 0, 0 };
static int[] dy = { 0, 1, 0, -1, 0, 0 };
static int[] dz = { 0, 0, 0, 0, -1, 1 };
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int h = sc.nextInt();
Queue<Three> queue = new LinkedList<Three>();
int[][][] arr = new int[h][n][m];
int[][][] dist = new int[h][n][m];
for (int k = 0; k < h; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[k][i][j] = sc.nextInt();
if (arr[k][i][j] == 1)
queue.add(new Three(k, i, j));
}
}
}
while (!queue.isEmpty()) {
Three t = queue.remove();
int x = t.x;
int y = t.y;
int z = t.z;
for (int i = 0; i < dy.length; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
int nz = z + dz[i];
if (0 <= nx && nx < h && 0 <= ny && ny < n && 0 <= nz && nz < m) {
if (arr[nx][ny][nz] == 0 && dist[nx][ny][nz] == 0) {
queue.add(new Three(nx, ny, nz));
dist[nx][ny][nz] = dist[x][y][z] + 1;
}
}
}
}
int ans = 0;
for (int k = 0; k < h; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (ans < dist[k][i][j])
ans = dist[k][i][j];
}
}
}
for (int k = 0; k < h; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[k][i][j] == 0 && dist[k][i][j] == 0) {
ans = -1;
}
}
}
}
System.out.println(ans);
sc.close();
}
}
<참고>
https://developer-mac.tistory.com/68
[Java]백준 7569번 :: 토마토
백준 온라인 저지 7569번 - 토마토 Java 알고리즘 문제풀이 풀이 BFS(너비 우선 탐색) 문제입니다. BFS를 이용해 해결하는 문제는 3가지 조건을 가지고 있다. 1. 최소 비용 문제 2. 간선의 가중치가 1
developer-mac.tistory.com
'알고리즘 > 백준' 카테고리의 다른 글
[DFSBFS] 백준_9372_상근이의여행_MST_실버4 (0) | 2021.10.23 |
---|---|
[DFSBFS] 백준_7576_토마토DFSBFS_실버1 (0) | 2021.10.23 |
[DFSBFS] 백준_2178_미로탐색_DFSBFS_실버1 (0) | 2021.10.19 |
[DFSBFS] 백준_1012_유기농배추_DFSBFS_실버2 (0) | 2021.10.19 |
[DFSBFS] 백준_2667_단지번호붙이기_DFSBFS_실버1 (0) | 2021.10.16 |