티스토리 뷰

백준

백준 소스코드 [C++] 2638 치즈

Hani_Levenshtein 2021. 1. 5. 15:20

www.acmicpc.net/problem/2638

 

2638번: 치즈

첫째 줄에는 모눈종이의 크기를 나타내는 두 개의 정수 N, M (5≤N, M≤100)이 주어진다. 그 다음 N개의 줄에는 모눈종이 위의 격자에 치즈가 있는 부분은 1로 표시되고, 치즈가 없는 부분은 0으로 표

www.acmicpc.net

백준 소스코드 [C++] 2638 치즈

#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <limits.h>
#include <vector>
#include <math.h>
#include <stack>
#include <bitset>
#include <string>
#include <set>
#define all(v) v.begin(), v.end()
#define pii pair<int,int>
#define make_unique(v) v.erase(unique(v.begin(), v.end()), v.end())
typedef long long ll;
using namespace std;

int arr[102][102];
int one[102][102];
bool chk[102][102];
int cheese = 0;
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };

typedef struct dot {
	int y, x;
}dot;

void bfs() {
	queue<dot>q;
	q.push({ 1,1 });
	chk[1][1] = true;
	while (q.empty() != true) {
		dot a = q.front();
		q.pop();
		for(int i=0;i<4;i++)
			if (chk[a.y + dy[i]][a.x + dx[i]] == false) {
				if (arr[a.y + dy[i]][a.x + dx[i]] == 0) {
					chk[a.y + dy[i]][a.x + dx[i]] = true;
					q.push({ a.y + dy[i],a.x + dx[i] });
				}
				else if (arr[a.y + dy[i]][a.x + dx[i]] == 1) {
					one[a.y + dy[i]][a.x + dx[i]]++;
					if (2 == one[a.y + dy[i]][a.x + dx[i]]) {
						arr[a.y + dy[i]][a.x + dx[i]] = 0;
						chk[a.y + dy[i]][a.x + dx[i]] = true;
						one[a.y + dy[i]][a.x + dx[i]] = 0;
						cheese--;
					}
				}
			}
	}

	memset(chk, false, sizeof(chk));
	memset(one, 0, sizeof(one));

}
int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n, m;
	cin >> n >> m;

	for (int i = 0;i <= n + 1;i++)
		for (int j = 0;j <= m + 1;j++)
			arr[i][j] = 2;

	for (int i = 1;i <= n;i++)
		for (int j = 1;j <= m;j++) {
			cin >> arr[i][j];
			if (arr[i][j] == 1) cheese++;
		}

	int cnt = 0;
	while (0 < cheese) {
		bfs();
		cnt++;
	}
	cout << cnt;
	return 0;
}
댓글