Creative Code

[7576번]토마토 본문

백준 문제풀이

[7576번]토마토

빛하루 2023. 9. 24. 17:30

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

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토

www.acmicpc.net

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <algorithm>

using namespace std;

int arr[1001][1001];
int dx[4] = { 0,-1,0,1 };
int dy[4] = { 1,0,-1,0 };
int answer;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	int M, N;
	cin >> M >> N;
	answer = 0;
	queue<pair<int, int>>q;
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < M; j++) {
			int k;
			cin >> k;
			arr[i][j] = k;
			if (k == 1) {
				q.push(make_pair(i, j));
			}
		}
	}
	int index = 0;
	while (true) {
		queue<pair<int, int>>pq;
		while (!q.empty()) {
			int x = q.front().first;
			int y = q.front().second;
			q.pop();
			for (int i = 0; i < 4; i++) {
				int nx = x + dx[i];
				int ny = y + dy[i];
				if (nx == N || ny == M || nx == -1 || ny == -1) {
					continue;
				}
				else if (arr[nx][ny] == 0) {
					arr[nx][ny] = 1;
					pq.push(make_pair(nx, ny));
				}
			}
		}
		q = pq;
		if (pq.empty()) {
			break;
		}
		index++;
	}
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < M; j++) {
			if (arr[i][j] == 0) {
				index = -1;
				break;
			}
		}
	}
	cout << index;
}

'백준 문제풀이' 카테고리의 다른 글

[12856번]평범한 배낭  (0) 2023.09.24
[10026번]적록색약  (0) 2023.09.24
[7569번]토마토  (0) 2023.09.24
[5430번]AC  (0) 2023.09.24
[2166번]다각형의 면적  (0) 2023.09.24