토마토 (7569번)
https://www.acmicpc.net/problem/7569
풀이방법
- 숫자를 입력받을 때 익은 토마토의 좌표를
Queue
에 넣는다. Queue
에서 하나씩 빼면서 위,아래,상,하,좌,우에 현재값 +1 한다.- 방문하지 않은 곳은 -1로 설정한다.
- +1할때마다 최대값을 구한다.
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
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static Queue<int[]> queue = new LinkedList<>();
static int[][][] map;
static int[][][] dist;
static int zeroCount;
static int max = 0;
static int M = 0;
static int N = 0;
static int H = 0;
public static void main(String[] args) 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][N][M];
dist = new int[H][N][M];
zeroCount = 0;
for(int i=0; i<H; i++) {
for (int j=0; j<N; j++) {
st = new StringTokenizer(br.readLine());
for (int k=0; k<M; k++) {
map[i][j][k] = Integer.parseInt(st.nextToken());
if (map[i][j][k] == 0) {
dist[i][j][k] = -1;
zeroCount++;
}
if (map[i][j][k] == 1) {
dist[i][j][k] = 0;
queue.add(new int[] { k, j, i });
}
}
}
}
if (zeroCount == 0) {
System.out.println(0);
return;
}
bfs();
if (zeroCount != 0) System.out.println(-1);
else System.out.println(max);
}
private static void bfs() {
int[] cur;
int[] xPos = {1, 0, -1, 0, 0, 0};
int[] yPos = {0, 1, 0, -1, 0, 0};
int[] zPos = {0, 0, 0, 0, -1, 1};
int dx = 0; int dy = 0; int dz = 0;
while (!queue.isEmpty()) {
cur = queue.poll();
for(int i=0; i<6; i++) {
dx = cur[0] + xPos[i];
dy = cur[1] + yPos[i];
dz = cur[2] + zPos[i];
if (dx < 0 || dx >= M || dy < 0 || dy >= N || dz < 0 || dz >= H) continue;
if (dist[dz][dy][dx] != -1) continue;
dist[dz][dy][dx] = dist[cur[2]][cur[1]][cur[0]] + 1;
queue.add(new int[] { dx, dy, dz });
max = Math.max(max, dist[dz][dy][dx]);
zeroCount--;
}
}
}
}
Comments powered by Disqus.