본문 바로가기
개발 노트/백준, 프로그래머스 풀이

[백준 7569/c++] 토마토

by tokkiC 2022. 8. 10.

이전 7576 번 토마토 문제에서 3차원 배열이란 점만 달라진 문제

3차원 배열과 tuple 을 사용해서 z축을 구현하였다

풀이 자체는 이전 토마토와 같은 BFS 방식이다

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

 

7569번: 토마토

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

www.acmicpc.net

#include <bits/stdc++.h>
using namespace std;

int n, m, h;
int board[104][104][104];
int dist[104][104][104];
int dz[6] = {0, 0, 0, 0, -1, 1};
int dx[6] = {-1, 1, 0, 0, 0, 0};
int dy[6] = {0, 0, -1, 1, 0, 0};
int min_dist = 0;

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	queue<tuple<int, int, int>> Q;
		
	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 >> board[i][j][k];
				if (board[i][j][k] == 1)
				{
					Q.push(make_tuple(i, j, k));
				}
				if (board[i][j][k] == 0)
				{
					dist[i][j][k] = -1;
				}
			}
		}
	}
	while (!Q.empty()) {
		auto current = Q.front();
		Q.pop();
		for (int dir = 0; dir < 6; dir++)
		{
			int nz = get<0>(current) + dz[dir];
			int nx = get<1>(current) + dx[dir];
			int ny = get<2>(current) + dy[dir];
			if (nz < 0 || nz >= h || nx < 0 || nx >= n || ny < 0 || ny >= m)
			{
				continue;
			}
			if (dist[nz][nx][ny] >= 0) {
				continue;
			}
			dist[nz][nx][ny] = dist[get<0>(current)][get<1>(current)][get<2>(current)] + 1;
			Q.push(make_tuple(nz, nx, ny));
		}
	}
	for (int i = 0; i < h; i++)
	{
		for (int j = 0; j < n; j++)
		{
			for (int k = 0; k < m; k++)
			{
				if (dist[i][j][k] == -1)
				{
					cout << -1;
					return 0;
				}
			min_dist = max(min_dist, dist[i][j][k]);
			}
		}
	}
	cout << min_dist;
	
	return 0;
}

'개발 노트 > 백준, 프로그래머스 풀이' 카테고리의 다른 글

[백준 1158/c++] 요세푸스 문제  (0) 2022.08.12
[백준 4179/c++] 불!  (0) 2022.08.11
[백준 7576/c++] 토마토  (0) 2022.08.09
[백준 2178/c++] 미로 탐색  (0) 2022.08.08
[백준 1926/c++] 그림  (0) 2022.08.07

댓글