티스토리 뷰

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

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마

www.acmicpc.net

#include<iostream>
#include<queue>
#include<utility>
#include<vector>

using namespace std;

int M, N;
int direct[4][2] = { { 1,0 },{ -1,0 },{ 0,1 },{ 0,-1 } };
vector<vector<int>> Tomato;
queue<pair<int, int>> Q;

void BFS() {
	while (!Q.empty()) {
		pair<int, int> know = Q.front();
		Q.pop();

		for (int i = 0; i < 4; i++) {
			int n = know.first + direct[i][0];
			int m = know.second + direct[i][1];

			if (0 <= n && n < N && 0 <= m && m < M &&Tomato[n][m] != -1) {
				if (Tomato[n][m] == 0 || Tomato[n][m] > Tomato[know.first][know.second] + 1) {
					Q.push(make_pair(n, m));
					Tomato[n][m] = Tomato[know.first][know.second] + 1;
				}
			}
		}
	}
}

int main(void) {
	//입력
	cin >> M >> N;

	for (int i = 0; i < N; i++) {
		vector<int> temp;
		for (int j = 0; j < M; j++) {
			int x;
			cin >> x;
			temp.push_back(x);
		}
		Tomato.push_back(temp);
	}

	//BFS 호출
	for (int i = 0; i < Tomato.size(); i++) {
		for (int j = 0; j < Tomato[i].size(); j++) {
			if (Tomato[i][j] == 1)
				Q.push(make_pair(i, j));
		}
	}
	BFS();

	//정답출력
	int max = 0;

	for (int i = 0; i < Tomato.size(); i++) {
		for (int j = 0; j < Tomato[i].size(); j++) {
			if (Tomato[i][j] > max)
				max = Tomato[i][j];
			if (Tomato[i][j] == 0) {
				cout << -1 << endl;
				return 0;
			}
		}
	}

	if (max == 1)
		cout << 0 << endl;
	else
		cout << max - 1 << endl;

}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함