반응형

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

 

1012번: 유기농 배추

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

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 입력받은 좌표를 1로 바꾸어 배추의 위치를 기록합니다.

 

2. bfs를 통해 배추가 있는 곳을 0으로 갱신해주면서 연결되어 있는 배추들의 개수를 cnt에 저장합니다.

 

3. cnt를 출력합니다.

 

[ 소스코드 ]

 

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
#include<queue>
#include<cstring>
 
using namespace std;
 
int N, M, K;
 
int arr[50][50];
int dy[4= { -1,1,0,0 };
int dx[4= { 0,0,-1,1 };
 
void bfs(int y, int x)
{
    queue<pair<intint>> q;
    q.push({ y,x });
    arr[y][x] = 0;
 
    while (!q.empty())
    {
        int y = q.front().first;
        int x = q.front().second;
        q.pop();
 
        for (int i = 0; i < 4; i++) {
            int yy = y + dy[i];
            int xx = x + dx[i];
            if (yy >= 0 && yy < N && xx >= 0 && xx < M) {
                if (arr[yy][xx] == 1) {
                    arr[yy][xx] = 0;
                    q.push({ yy,xx });
                }
            }
        }
    }
}
 
int main()
{
    int T;
    scanf("%d"&T);
 
    for (int t = 0; t < T; t++) {
        scanf("%d %d %d"&M, &N, &K);
        memset(arr, 0sizeof(arr));
        
        for (int i = 0; i < K; i++) {
            int x, y;
            scanf("%d %d"&x, &y);
 
            arr[y][x] = 1;
        }
 
        int cnt = 0;
 
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (arr[i][j] == 1) {
                    bfs(i, j);
                    cnt++;
                }
            }
        }
 
        printf("%d\n", cnt);
    }
}
cs
반응형

+ Recent posts