반응형

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

 

7569번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. tomato struct를 만들어서 z, y, x 좌표와 토마토가 익는 데 걸리는 시간 cnt를 저장합니다.

 

2. 1을 입력 받으면 queue에 z, y, x 좌표를 넣고, visited 배열을 1로 갱신해줍니다.

 

3. bfs를 이용해서 익지 않은 토마토가 인접해 있다면 1로 바꾸고, queue에 넣어줍니다.

 

4. 위 과정을 반복해줍니다.

 

[ 소스코드 ]

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
79
80
81
82
83
84
85
86
87
88
89
90
#include<iostream>
#include<queue>
 
using namespace std;
 
struct tomato {
    int z;
    int y;
    int x;
    int cnt;
};
 
int N, M, H;
int arr[100][100][100];
int visited[100][100][100];
int dz[6= { 0,0,0,0,-1,1 };
int dy[6= { -1,1,0,0,0,0 };
int dx[6= { 0,0,-1,1,0,0 };
int ans = -1;
queue<tomato> q;
 
 
bool check()
{
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < N; j++) {
            for (int k = 0; k < M; k++) {
                if (arr[i][j][k] == 0) {
                    return false;
                }
            }
        }
    }
 
    return true;
}
 
int main()
{
    scanf("%d %d %d"&M, &N, &H);
 
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < N; j++) {
            for (int k = 0; k < M; k++) {
                scanf("%d"&arr[i][j][k]);
 
                if (arr[i][j][k] == 1) {
                    q.push({ i,j,k,0 });
                    visited[i][j][k] = 1;
                }
            }
        }
    }
 
    if (check()) {
        printf("%d"0);
        return 0;
    }
 
    while (!q.empty()) {
        int z = q.front().z;
        int y = q.front().y;
        int x = q.front().x;
        int cnt = q.front().cnt;
        q.pop();
 
        ans = max(ans, cnt);
 
        for (int i = 0; i < 6; i++) {
            int zz = z + dz[i];
            int yy = y + dy[i];
            int xx = x + dx[i];
 
            if (zz >= 0 && zz < H && yy >= 0 && yy < N && xx >= 0 && xx < M) {
                if (visited[zz][yy][xx] != 1 && arr[zz][yy][xx] == 0) {
                    arr[zz][yy][xx] = 1;
                    visited[zz][yy][xx] = 1;
                    q.push({ zz,yy,xx,cnt + 1 });
                }
            }
        }
    }
 
    if (check()) {
        printf("%d", ans);
    }
    else {
        printf("%d"-1);
    }
}
cs
반응형

+ Recent posts