본문 바로가기

Algorithm/BAEKJOON

[BOJ] 1012번 유기농 배추 (C++)

728x90
반응형

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

 

1012번: 유기농 배추

차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 

www.acmicpc.net

 

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

// 상하좌우
int dx[] = { 0, -1, 1, 0 };
int dy[] = { -1, 0, 0, 1 };

int m, n;
int map[51][51];

void bfs(int x, int y) {
	map[x][y] = 0;

	queue<pair<int, int>> q;
	q.push(pair<int, int>(x, y));

	int cx, cy, ax, ay;
	while (!q.empty()) {
		cx = q.front().first;
		cy = q.front().second;
		q.pop();

		for (int i = 0; i < 4; i++) {
			ax = cx + dx[i];
			ay = cy + dy[i];

			if (ax >= 0 && ay >= 0 && ax < m && ay < n && map[ax][ay] == 1) {
				map[ax][ay] = 0;
				q.push(pair<int, int>(ax, ay));
			}
		}
	}
}

int main(){
	int t, k, x, y;
	cin >> t;

	for (int i = 0; i < t; i++) {
		cin >> m >> n >> k;
		int cnt = 0;

		for (int j = 0; j < k; j++) {
			cin >> x >> y;
			map[x][y] = 1;
		}

		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (map[i][j] == 1) {
					bfs(i, j);
					cnt++;
				}
			}
		}

		cout << cnt << endl;
	}
	return 0;
}
728x90
반응형

'Algorithm > BAEKJOON' 카테고리의 다른 글

[BOJ] 1966번 프린터 큐 (C++)  (0) 2021.11.03
[BOJ] 4963번 섬의 개수 (C++)  (0) 2021.11.03
[BOJ] 10867번 중복 빼고 정렬하기 (C++)  (0) 2021.11.02
[BOJ] 1260번 DFS와 BFS (C++)  (0) 2021.11.01
[BOJ] 2606번 바이러스 (C++)  (0) 2021.11.01