BOJ 7569 토마토

1 개요[ | ]

BOJ 7569 토마토

2 C++[ | ]

#include <bits/stdc++.h>
using namespace std;

int M, N, H;
int A[100][100][100];
int want = 0;
int got = 0;
int days = 1;
queue<tuple<int,int,int>> q;

int dx[6] = {1, -1, 0, 0, 0, 0};
int dy[6] = {0, 0, 1, -1, 0, 0};
int dz[6] = {0, 0, 0, 0, 1, -1};

void bfs() {
    int x, y, z, nx, ny, nz;
    while(!q.empty()) {
        tuple<int,int,int> t = q.front();
        q.pop();
        x = get<0>(t);
        y = get<1>(t);
        z = get<2>(t);
        for(int i=0; i<6; i++) {
            nx = x + dx[i];
            ny = y + dy[i];
            nz = z + dz[i];
            if(nx<0 || nx>=M || ny<0 || ny>=N || nz<0 || nz>=H || A[nx][ny][nz] != 0) continue;
            A[nx][ny][nz] = A[x][y][z] + 1;
            q.push({nx, ny, nz});
            got++;
            if(A[nx][ny][nz] > days) days = A[nx][ny][nz];
        }
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    cin >> M >> N >> H;
    for(int z=0; z<H; z++) {
        for(int y=0; y<N; y++) {
            for(int x=0; x<M; x++) {
                cin >> A[x][y][z];
                if(A[x][y][z] == 0) {
                    want++;
                } else if(A[x][y][z] == 1) {
                    q.push({x,y,z});
                }
            }
        }
    }
    bfs();
    cout << ((want == got) ? days-1 : -1);
}