https://www.acmicpc.net/problem/7569
7576번 문제의 3차원 배열 버전이다
푸는 방식은 동일하지만, 높이를 고려해야 하기때문에 배열을 3차원으로 선언하여 x,y 뿐만아니라 z까지 이동하는
방법으로 풀었다. static int N , M, H, 을 선언하고 int N, M, H 를 또 선언해줘서 괜한 시간 낭비를 했었다 ..
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int M, N, H;
static int cnt = 0;
static int map[][][];
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 };
static boolean visited[][][];
static Queue<int[]> qu = new LinkedList<int[]>();
public static void main(String agrs[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
H = Integer.parseInt(st.nextToken());
map = new int[H + 1][N + 1][M + 1];
for (int i = 1; i <= H; i++) {
for (int j = 1; j <= N; j++) {
st = new StringTokenizer(br.readLine());
for (int k = 1; k <= M; k++) {
map[i][j][k] = Integer.parseInt(st.nextToken());
if (map[i][j][k] == 1) {
qu.add(new int[] { i, j, k });
}
}
}
}
BFS();
Loop1: for (int i = 1; i <= H; i++) {
for (int j = 1; j <= N; j++) {
for (int k = 1; k <= M; k++) {
cnt = Math.max(map[i][j][k], cnt);
if (map[i][j][k] == 0) {
cnt = -1;
break Loop1;
}
}
}
}
if (cnt != -1)
System.out.println(cnt - 1);
else
System.out.println(cnt);
}
static void BFS() {
while (!qu.isEmpty()) {
int curH = qu.peek()[0];
int curY = qu.peek()[1];
int curX = qu.peek()[2];
qu.poll();
for (int i = 0; i < 6; i++) {
int nh = curH + dz[i];
int ny = curY + dy[i];
int nx = curX + dx[i];
if (nh <= 0 || ny <= 0 || nx <= 0 || nh > H || ny > N || nx > M)
continue;
if (map[nh][ny][nx] != 0)
continue;
qu.add(new int[] { nh, ny, nx });
map[nh][ny][nx] = map[curH][curY][curX] + 1;
}
}
}
}
'프로그래밍 & IT > Algorithm' 카테고리의 다른 글
[알고리즘] 백준 2206번 벽 부수고 이동하기 :: 우유 (0) | 2022.04.17 |
---|---|
[알고리즘] 백준 1697번 숨바꼭질 :: 우유 (0) | 2022.04.09 |
[알고리즘] 백준 7576번 토마토 :: 우유 (0) | 2022.04.07 |
[알고리즘] 백준 2606번 바이러스 :: 우유 (0) | 2022.03.29 |
[알고리즘] 백준 18870번 좌표 압축 :: 우유 (0) | 2022.03.08 |