백준/BFS
[백준 7569] 토마토
mintuchel
2025. 5. 12. 20:44
3차원 토마토인데 이것도 푸는 방식은 2차원 토마토와 동일함.
day를 pair<int,int,int> 와 같이 넣어줌으로써 while 문안에 bfs를 돌리면서 day를 count 하지 않아도 되게끔 함.
이게 훨씬 나은 방식인듯??
#include <iostream>
#include <queue>
#include <tuple>
#define SIZE 101
using namespace std;
int map[SIZE][SIZE][SIZE];
int visited[SIZE][SIZE][SIZE];
int M, N, H;
int dy[4] = {-1, 1, 0, 0};
int dx[4] = {0, 0, -1, 1};
int dz[2] = {-1, 1};
queue<pair<tuple<int, int, int>, int>> q;
void solve()
{
int ans = -1;
while (!q.empty())
{
tuple<int, int, int> t = q.front().first;
int curh = get<0>(t);
int cury = get<1>(t);
int curx = get<2>(t);
int day = q.front().second;
q.pop();
if (day > ans)
{
ans = day;
}
int newy, newx, newh;
for (int i = 0; i < 4; i++)
{
newy = cury + dy[i];
newx = curx + dx[i];
if (newy < 0 || newy >= N || newx < 0 || newx >= M)
continue;
if (map[curh][newy][newx] == 0)
{
map[curh][newy][newx] = 1;
q.push(make_pair(make_tuple(curh, newy, newx), day + 1));
}
}
for (int i = 0; i < 2; i++)
{
newh = curh + dy[i];
if (newh < 0 || newh >= H)
continue;
if (map[newh][cury][curx] == 0)
{
map[newh][cury][curx] = 1;
q.push(make_pair(make_tuple(newh, cury, curx), day + 1));
}
}
}
for (int h = 0; h < H; h++)
{
for (int i = 0; i < N; i++)
{
for (int k = 0; k < M; k++)
{
if (map[h][i][k] == 0)
{
cout << "-1";
return;
}
}
}
}
cout << ans;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
// 가로 세로 높이
cin >> M >> N >> H;
for (int h = 0; h < H; h++)
{
for (int i = 0; i < N; i++)
{
for (int k = 0; k < M; k++)
{
cin >> map[h][i][k];
if (map[h][i][k] == 1)
{
q.push(make_pair(make_tuple(h, i, k), 0));
}
}
}
}
solve();
return 0;
}