[C++]BOJ 1012 - 유기농 배추

[C++]BOJ 1012 - 유기농 배추

배열을 순회하며 배추를 만나면 그 지점부터 bfs나 dfs를 돌리며 모두 0으로 초기화한다.
이 과정을 반복해 모둔 배추 영역을 찾은 후 그 영역의 갯수를 출력하면 된다.
bfs와 dfs모두 다뤄보겠다.


bfs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int t, m, n, k, sx, sy, xx, yy, cx, cy, arr[52][52], dx[4] = {0, 0, -1, 1}, dy[4] = {-1, 1, 0, 0}, ans;
queue<int> qx, qy;
void bfs(int x, int y) {
while(!qx.empty()) {
sx = qx.front(); qx.pop();
sy = qy.front(); qy.pop();
for(int i = 0; i < 4; i++) {
xx = sx + dx[i];
yy = sy + dy[i];
if(xx > m || yy > n || xx < 1 || yy < 1 || !arr[yy][xx]) continue;
arr[yy][xx] = 0;
qx.push(xx), qy.push(yy);
}
}
}
int main() {
cin >> t;
while(t--) {
memset(arr, 0, sizeof(arr));
ans = 0;
cin >> m >> n >> k;
while(k--) {
cin >> cx >> cy;
arr[cy + 1][cx + 1] = 1;
}
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(arr[i][j]) {
qx.push(j), qy.push(i);
bfs(j, i);
ans++;
}
cout << ans << endl;
}
}

dfs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cstring>
using namespace std;
int t, m, n, k, cx, cy, xx, yy, arr[52][52], dx[4] = {0, 0, -1, 1}, dy[4] = {-1, 1, 0, 0}, ans;
void dfs(int x, int y) {
arr[y][x] = 0;
for(int i = 0; i < 4; i++) {
xx = x + dx[i];
yy = y + dy[i];
if(xx > m || yy > n || xx < 1 || yy < 1 || !arr[yy][xx]) continue;
dfs(xx, yy);
}
}
int main() {
cin >> t;
while(t--) {
ans = 0;
cin >> m >> n >> k;
memset(arr, 0, sizeof(arr));
while(k--) {
cin >> cx >> cy;
arr[cy + 1][cx + 1] = 1;
}
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(arr[i][j]) {
dfs(j, i);
ans++;
}
cout << ans << endl;
}
}