가취공부하자

[백준] 7569 토마토 c++ 본문

알고리즘/백준

[백준] 7569 토마토 c++

keepGGoing 2021. 6. 28. 12:00

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

 

7569번: 토마토

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

www.acmicpc.net

 

bfs 사용

 

#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<pair<pair<int, int>, int>, int> Info;

int x, y, z;
bool visit[101][101][101] = { false, };
int tomato[101][101][101] = { 0, };

int dx[6] = { 1,-1,0,0,0,0 };
int dy[6] = { 0,0,1,-1,0,0 };
int dz[6] = { 0,0,0,0,1,-1 };

int main() {
	queue<Info>q;
	int count = 0, day = 0, empty = 0,finish_day;
	cin >> x >> y >> z;
	//토마토 입력
	for (int i = 0; i < z; i++)
	{
		for (int j = 0; j < y; j++)
		{
			for (int k = 0; k < x; k++)
			{
				cin >> tomato[j][k][i];
				if (tomato[j][k][i] == 1) {
					q.push({ {{j,k},i },day });
					visit[j][k][i] == true;
				}
				else if (tomato[j][k][i] == -1)
					empty++;
			}
		}
	}

	int col, row, height, new_col, new_row, new_height;
	while (!q.empty()) {
		col = q.front().first.first.second;
		row = q.front().first.first.first;
		height = q.front().first.second;
		day = q.front().second;
		finish_day = max(finish_day, day);
		count = count + 1;
		q.pop();
		for (int i = 0; i < 6; i++)
		{
			new_col = col + dx[i];
			new_row = row + dy[i];
			new_height = height + dz[i];
			if (new_col >= 0 && new_row >= 0 && new_height >= 0 && new_col < x &&new_row < y&&new_height < z) {
				if (!visit[new_row][new_col][new_height] && tomato[new_row][new_col][new_height]==0) {
					q.push({ {{new_row,new_col},new_height },day+1});
					visit[new_row][new_col][new_height] = true;
				}
			}

		}
	}
	if (count == x * y*z - empty)
		cout << finish_day;
	else
		cout << -1;


	return 0;
}

 

더보기

x, y, z로 하고 row, col, height 로하니까 헷갈려 힘들었음.. 그래서 옆에 적어놓고 했음

'알고리즘 > 백준' 카테고리의 다른 글

[5636] c++ 소수 부분 문자열  (0) 2021.11.05
[백준] 9663 N-Queen c++  (0) 2021.10.04
[백준]12865 평범한 배낭 c++  (0) 2021.06.21
[백준] 1300 K번째 수 c++  (0) 2021.04.07
[백준] 2146 다리만들기 c++  (0) 2021.04.01