본문 바로가기
PS/BOJ

[백준] 7569. 토마토(c++)

by backend 개발자 지망생 2025. 3. 2.

https://www.acmicpc.net/problem/7569

3차원 토마토다..!

이전에 풀었을 때는 구조체로 3차원 배열을 받을 수 있게 했었는데, pair 안에 pair를 쓰는 것은 depth가 깊어져 지양해야 겠다는 생각을 했다.

구조체를 활용하자


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <limits.h>
#include <queue>
#include <set>
#include <math.h>
#include <stack>
#include <deque>

using namespace std;

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

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int n, m, h, ans = 0, chk = 0, cnt = 0;

    queue<pair<int, pair<int, int> > > q;

    cin >> m >> n >> h;
    for (int k = 0; k < h; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cin >> arr[k][i][j];
                if (arr[k][i][j] == 1) {
                    q.push({k, {i, j}});
                }
                if (arr[k][i][j] == -1)
                    cnt++;
                if (arr[k][i][j] == 0)
                    chk++;
            }
        }
    }

    if (!chk) {
        cout << 0;
        return 0;
    }


    while (!q.empty()) {
        int z = q.front().first;
        int y = q.front().second.first;
        int x = q.front().second.second;

        q.pop();

        for (int i = 0; i < 6; i++) {
            int nz = z + dz[i];
            int ny = y + dy[i];
            int nx = x + dx[i];

            if (nz < 0 || nz >= h || ny < 0 || ny >= n || nx < 0 || nx >= m) continue;
            if (visited[nz][ny][nx] || arr[nz][ny][nx] == -1 || arr[nz][ny][nx] == 1) continue;
            visited[nz][ny][nx] = 1;
            arr[nz][ny][nx] = arr[z][y][x] + 1;
            // ans = max(ans, arr[ny][nx]);
            q.push({nz, {ny, nx}});
        }
    }

    for (int k = 0; k < h; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                ans = max(ans, arr[k][i][j]);

                if (arr[k][i][j] == 0) {
                    cout << -1;
                    return 0;
                }
            }
        }
    }

    cout << ans - 1 << '\n';

    return 0;
}

'PS > BOJ' 카테고리의 다른 글

[백준] 5427. 불(c++)  (0) 2025.03.02
[백준] 7562. 나이트의 이동(c++)  (0) 2025.03.02
[백준] 10026. 적록색약(c++)  (0) 2025.03.02
[백준]5014. 스타트링크(c++)  (0) 2025.02.26
[백준]1012. 유기농배추(c++)  (0) 2025.02.24