알고리즘 공부

백준 토마토

컴퓨터과학 2023. 7. 4. 22:44

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

 

7576번: 토마토

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

www.acmicpc.net

음 bfs 좀 생각하는문제 그닥 어렵진 않네요 . ㅎ ㅎ 

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

struct Point {
	int m, n;
};
void Prints(vector<vector<int>>maps,int n,int m) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cout << maps[i][j] << ",";
		}
		cout << endl;
	}
}

int main() {
	int m, n;
	vector<vector<int>>maps;
	int zeroCount = 0;
	int confirmZCount = 0;

	cin >> m >> n;
	
	for (int i = 0; i < n; i++) {
		vector<int>tmpMaps;
		for (int j = 0; j < m; j++) {
			int tmp;
			cin >> tmp;
			if (tmp == 0) {
				zeroCount++;
			}
			tmpMaps.push_back(tmp);
		}
		maps.push_back(tmpMaps);
	}

	queue<Point> q;
	int dirm[] = {0,0,1,-1};
	int dirn[] = {1,-1,0,0};
	//최초 init
	int gCount =0;
	for (int i = 0; i < n; i++) {
		Point p;
		for (int j = 0; j < m; j++) {
			if (maps[i][j] == 1) {
				p.m = j;
				p.n = i;
				q.push(p);
			}
		}
	}
	
	
	while (!q.empty()) {
		bool bCheck = true;
		queue <Point>tmpQ;
		Point start;
		int cnt = q.size();
		for (int i = 0; i < cnt; i++) {
			
			start = q.front();
			tmpQ.push(start);
			q.pop();
		}
		while (!tmpQ.empty()) {
			start = tmpQ.front();
			tmpQ.pop();
			for (int i = 0; i < 4; i++) {
				int tmpM = start.m + dirm[i];
				int tmpN = start.n + dirn[i];
				if (tmpM == -1 || tmpN == -1 || tmpM >= m || tmpN >= n || maps[tmpN][tmpM] != 0) {
					continue;
				}

				if (maps[tmpN][tmpM] == 0) {
					confirmZCount++;
					Point tmp;
					tmp.m = tmpM;
					tmp.n = tmpN;
					maps[tmpN][tmpM] = 1;
					q.push(tmp);

					if (bCheck == true) {
						gCount++;
						bCheck = false;
					}
				}
			}
		}
	}

	if (confirmZCount == zeroCount) {
		cout << gCount;
	}
	else {
		cout << -1;
	}
	return 0;
}