문제
https://www.acmicpc.net/problem/1012
1012번: 유기농 배추
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 효과적인 배추흰지렁이를 구입하기로 결심한다. 이 지렁이는 배추근처에 서식하며 해충을 잡아 먹음으로써 배추를 보호한다. 특히, 어떤 배추에 배추흰지렁이가 한 마리라도 살고 있으면 이 지렁이는 인접한 다른 배추로 이동할 수 있어, 그 배추들 역시 해충으로부터 보호받을 수 있다. (
www.acmicpc.net
소스코드
#include <iostream>
#include <queue>
using namespace std;
int dx[] = { -1, 0, 1, 0 };
int dy[] = { 0, -1, 0, 1 };
queue<pair<int, int>> q;
int N, M, K;
int cabbage[50][50];
bool visited[50][50];
void bfs(int xx, int yy) {
q.push({ xx, yy });
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
visited[x][y] = true;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < N && ny < M && !visited[nx][ny] && cabbage[nx][ny] == 1) {
visited[nx][ny] = true;
q.push({ nx, ny });
}
}
}
}
void init() {
while (!q.empty()) q.pop();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
visited[i][j] = false;
cabbage[i][j] = 0;
}
}
}
int main(void) {
int T;
cin >> T;
for (int t = 0; t < T; t++) {
init();
cin >> M >> N >> K;
int cnt = 0;
for (int j = 0; j < K; j++) {
int x, y;
cin >> y >> x;
cabbage[x][y] = 1;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (cabbage[i][j] == 1 && !visited[i][j]) {
bfs(i, j);
cnt++;
}
}
}
cout << cnt << endl;
}
}
'개인 공부 > 코딩테스트' 카테고리의 다른 글
[C++][프로그래머스][Dynamic Programming] 정수삼각형 :: seoftware (0) | 2020.02.29 |
---|---|
[C++][프로그래머스][Dynamic Progamming] 타일 장식물 :: seoftware (0) | 2020.02.29 |
[C++][백준 1697][BFS DFS] 숨바꼭질 :: seoftware (0) | 2020.02.29 |
[C++][백준 7576][BFS / DFS] 토마토 :: seoftware (0) | 2020.02.29 |
[C++][백준 1026 ][정렬] 보물 :: seoftware (0) | 2020.02.29 |
댓글