[C++]BOJ 7569 - 토마토

[C++]BOJ 7569 - 토마토

재밌는 문제다.
같은 이름의 문제가 두 개인데 이 문제 -> 토마토는 2차원 공간에서의 탐색이라면 지금 이 문제는 3차원 공간에서의 탐색이다.
기본적인 풀이는 2차원 토마토와 같고 축 하나만 더 추가하면 된다.
bfs로 풀었다.


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
#include <iostream>
#include <queue>
using namespace std;
int dx[6] = {0, 0, 0, 0, -1, 1}, dy[6] = {0, 0, -1, 1, 0, 0}, dz[6] = {-1, 1, 0, 0, 0, 0};
int m, n, h, cx, cy, cz, xx, yy, zz, arr[102][102][102], ans;
queue<int> qx, qy, qz;
int main() {
cin >> m >> n >> h;
for(int z = 1; z <= h; z++)
for(int y = 1; y <= n; y++)
for(int x = 1; x <= m; x++) {
cin >> arr[z][y][x];
if(arr[z][y][x] == 1) qx.push(x), qy.push(y), qz.push(z);
}
while(!qx.empty()) {
cx = qx.front(); qx.pop();
cy = qy.front(); qy.pop();
cz = qz.front(); qz.pop();
for(int i = 0; i < 6; i++) {
xx = cx + dx[i]; yy = cy + dy[i]; zz = cz + dz[i];
if(xx < 1 || yy < 1 || zz < 1 || xx > m || yy > n || zz > h || arr[zz][yy][xx]) continue;
qx.push(xx), qy.push(yy), qz.push(zz);
arr[zz][yy][xx] = arr[cz][cy][cx] + 1;
}
}
for(int z = 1; z <= h; z++)
for(int y = 1; y <= n; y++)
for(int x = 1; x <= m; x++) {
if(!arr[z][y][x]) {
cout << "-1";
return 0;
}
ans = max(ans, arr[z][y][x]);
}
cout << ans - 1;
}