[BOJ] 7569 토마토

Time Lapse :NONE

7569.cpp

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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <iostream>
#include <memory.h>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

bool noZero = true;
int N,M,H;
int arr[101][101][101];
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
int ans = 0;
queue<vector<int>> q;

void BFS()
{
while(!q.empty())
{
int cur_x = q.front()[0];
int cur_y = q.front()[1];
int cur_h = q.front()[2];
int days = q.front()[3];
ans = max(ans,days);
q.pop();
for(int i=0;i<6;i++)
{
if(i<4)
{
int next_x = cur_x + dx[i];
int next_y = cur_y + dy[i];
int next_h = cur_h;

if(next_x<0||next_y<0||next_h<0||next_x>=N||next_y>=M||next_h>=H)
continue;

if(arr[next_x][next_y][next_h]==0)
{
vector<int> item;
item.push_back(next_x);
item.push_back(next_y);
item.push_back(next_h);
item.push_back(days+1);
arr[next_x][next_y][next_h]=days+1;
q.push(item);
}
}
else
{
int next_x = cur_x;
int next_y = cur_y;
int next_h = (i==4)?cur_h-1:cur_h+1;

if(next_x<0||next_y<0||next_h<0||next_x>=N||next_y>=M||next_h>=H)
continue;
if(arr[next_x][next_y][next_h]==0)
{
vector<int> item;
item.push_back(next_x);
item.push_back(next_y);
item.push_back(next_h);
item.push_back(days+1);
arr[next_x][next_y][next_h]=days+1;
q.push(item);
}
}
}
}
}


int main(void) {
cin>>M>>N>>H;
for(int i=0;i<H;i++) {
for(int j=0;j<N;j++) {
for (int k = 0; k < M; k++) {
cin >> arr[j][k][i];
if(arr[j][k][i]==0)
noZero=false;
if(arr[j][k][i]==1)
{
vector<int> start;
start.push_back(j);
start.push_back(k);
start.push_back(i);
start.push_back(1);
q.push(start);
}
}
}
}
if(noZero) {
cout << "0" << endl;
return 0;
}


BFS();

for(int i=0;i<H;i++)
{
for(int j=0;j<N;j++) {
for (int k = 0; k < M; k++) {
if(arr[j][k][i]==0)
{
cout<<"-1"<<endl;
return 0;
}
}

}
}
cout<<ans-1<<endl;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/30/PS/BOJ/7569/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.