거북이의 IT 공부
[백준 1012] 유기농 배추 - C++ / 알고리즘 BFS 본문
문제
https://www.acmicpc.net/problem/1012
1012번: 유기농 배추
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 효과적인 배추흰지렁이를 구입하기로 결심한다. 이 지렁이는 배추근처에 서식하며 해충을 잡아 먹음으로써 배추를 보호한다. 특히, 어떤 배추에 배추흰지렁이가 한 마리라도 살고 있으면 이 지렁이는 인접한 다른 배추로 이동할 수 있어, 그 배추들 역시 해충으로부터 보호받을 수 있다. (
www.acmicpc.net
나의 코드
#include <iostream> #include <vector> #include <queue> using namespace std; queue <pair<int, int> > q; int farm[50][50]; int direct[4][2] = { {1,0},{-1,0},{0,1},{0,-1} }; int breadth_first_search(int width, int height, int number) { for (int i = 0; i < number; i++) { int x, y; cin >> x >> y; farm[y][x] = 1; } int bug_count = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (farm[y][x] == 1) { q.push(make_pair(x, y)); farm[y][x] = 0; //들른 곳 bug_count++; while (!q.empty()) { pair<int, int> now = q.front(); q.pop(); for (int i = 0; i < 4; i++) { pair<int, int> next = make_pair(now.first + direct[i][0], now.second + direct[i][1]); if (next.first >= 0 && next.first < width && next.second >= 0 && next.second < height && farm[next.second][next.first] == 1) { farm[next.second][next.first] = 0; q.push(next); } } } } } } return bug_count; } int main(void) { int num; cin >> num; for (int i = 0; i < num; i++) { int m, n, k; cin >> m >> n >> k; for (int y = 0; y < n; y++) for (int x = 0; x < m; x++) farm[y][x] = 0; cout << breadth_first_search(m, n, k) << '\n'; } }
까먹을 법한 bfs의 감을 되살리기에 좋은 문제였다.
'Baekjoon' 카테고리의 다른 글
[백준 13913] 숨바꼭질 4 - C++ / 알고리즘 BFS (0) | 2020.04.25 |
---|---|
[백준 1697] 숨바꼭질 - C++ / 알고리즘 BFS (0) | 2020.04.24 |
[백준 10026] 적록색약 - C++ / 알고리즘 BFS (0) | 2020.04.15 |
[백준 1926] 그림 - C++ / 알고리즘 BFS, 플러드 필 (0) | 2020.04.15 |
[백준 2178] 미로탐색 - C++ / 알고리즘 BFS (0) | 2020.04.15 |
Comments