몽셀통통의 블로그

[BaekJoon] 7569 토마토 :: monton 본문

프로그래밍/백준 문제 풀기

[BaekJoon] 7569 토마토 :: monton

몽통이 2018. 6. 10. 21:40



문제

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



풀이

전형적이고 간단한 bfs 문제

상하좌우 뿐만아니라 앞뒤까지 포함하여 총 6방향으로 bfs로 돌리면된다

큐를 시작하면서 모든 토마토가 익었다면 return



코드

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
#include<iostream>
#include<queue>
using namespace std;
 
int M,N,H,ans;
int arr[101][101][101];
int visit[101][101][101];
int dir[6][3]={{-1,0,0},{1,0,0},{0,-1,0},{0,0,1},{0,1,0},{0,0,-1}};
 
int chkzero(){
    for(int k=0;k<H;k++){
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                if(arr[k][i][j]==0return 0;
            }
        }
    }
    return 1;
}
 
int main(){
    cin>>M>>N>>H;
    queue <int> qz,qx,qy;
    
    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) qz.push(k),qx.push(i),qy.push(j);
            }
        }
    }
    
    while(!qz.empty()){
        int qcnt=qz.size();
        if(chkzero()){
            cout<<ans;
            return 0;
        }
        while(qcnt--){
            int z=qz.front();
            int x=qx.front();
            int y=qy.front();
            
            qz.pop(),qx.pop(),qy.pop();
            
            for(int i=0;i<6;i++){
                int nz=z+dir[i][0];
                int nx=x+dir[i][1];
                int ny=y+dir[i][2];
                
                if(nz<0||nz>=H||nx<0||nx>=N||ny<0||ny>=M) continue;
                if(arr[nz][nx][ny]==-1||visit[nz][nx][ny]) continue;
                
                qz.push(nz),qx.push(nx),qy.push(ny);
                visit[nz][nx][ny]=1;
                arr[nz][nx][ny]=1;
            }
        }
        ans++;
    }
    cout<<"-1";
}
cs