Recent Posts
Notice
No Rules Rules
유기농 배추 (feat. 백준, 1012번) 본문
728x90
반응형
유기농 배추
https://www.acmicpc.net/problem/1012
1012번: 유기농 배추
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에
www.acmicpc.net
반응형
// woohyeon.kim
// kim519620.tistory.com
#include <iostream>
using namespace std;
int T, M, N, K, arr[50][50], dx[4], dy[4], ans;
bool visit[50][50];
bool dfs(register int x, register int y) {
if (visit[x][y]) return false;
visit[x][y] = true;
for (register int d = 0, nx, ny; d < 4; ++d) {
nx = x + dx[d], ny = y + dy[d];
if (0 <= nx && nx < N && 0 <= ny && ny < M && !visit[nx][ny] && arr[nx][ny] == 1)
dfs(nx, ny);
}
return true;
}
int main() {
ios::sync_with_stdio(false), cin.tie(NULL);
dx[0] = 1, dx[1] = -1, dx[2] = dx[3] = 0;
dy[0] = dy[1] = 0, dy[2] = 1, dy[3] = -1;
cin >> T;
for (register int t = 0; t < T; ++t) {
cin >> M >> N >> K;
for (register int n = 0, m; n < N; ++n)
for (m = 0; m < M; ++m)
arr[n][m] = 0, visit[n][m] = false;
for (register int k = 0, x, y; k < K; ++k)
cin >> x >> y, arr[y][x] = 1;
ans = 0;
for (register int n = 0, m; n < N; ++n)
for (m = 0; m < M; ++m)
if (arr[n][m] && dfs(n, m))
++ans;
cout << ans << "\n";
}
return 0;
}
// *&)*@*
DFS 풀이 방법
// woohyeon.kim
// kim519620.tistory.com
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int T, M, N, K, arr[50][50], dx[4], dy[4], ans;
bool visit[50][50];
bool bfs(register int x, register int y) {
if (visit[x][y]) return false;
visit[x][y] = true;
queue<pair<int, int>> q;
q.push(make_pair(x, y));
while (!q.empty()) {
auto v = q.front(); q.pop();
x = v.first, y = v.second;
for (register int d = 0, nx, ny; d < 4; ++d) {
nx = x + dx[d], ny = y + dy[d];
if (0 <= nx && nx < N && 0 <= ny && ny < M && !visit[nx][ny] && arr[nx][ny] == 1)
visit[nx][ny] = true, q.push(make_pair(nx, ny));
}
}
return true;
}
int main() {
ios::sync_with_stdio(false), cin.tie(NULL);
dx[0] = 1, dx[1] = -1, dx[2] = dx[3] = 0;
dy[0] = dy[1] = 0, dy[2] = 1, dy[3] = -1;
cin >> T;
for (register int t = 0; t < T; ++t) {
cin >> M >> N >> K;
for (register int n = 0, m; n < N; ++n)
for (m = 0; m < M; ++m)
arr[n][m] = 0, visit[n][m] = false;
for (register int k = 0, x, y; k < K; ++k)
cin >> x >> y, arr[y][x] = 1;
ans = 0;
for (register int n = 0, m; n < N; ++n)
for (m = 0; m < M; ++m)
if (arr[n][m] && bfs(n, m))
++ans;
cout << ans << "\n";
}
return 0;
}
// *&)*@*
BFS 풀이 방법
연결된 집합이 총 몇개인지를 구하는 문제이므로 DFS, BFS 모두 풀이가 가능합니다.
728x90
반응형
'생활 > 코테' 카테고리의 다른 글
숨바꼭질 (feat. 백준, 1697번) (0) | 2022.08.19 |
---|---|
미로 탐색 (feat. 백준, 2178번) (0) | 2022.08.19 |
단지번호붙이기 (feat. 백준, 2667번) (0) | 2022.08.19 |
DFS와 BFS (feat. 백준, 1260번) (0) | 2022.08.18 |
바이러스 (feat. 백준, 2606번) (0) | 2022.08.18 |
Comments