뜌릅

유기농 배추 1012번 [백준] 본문

알고리즘/PS 문제

유기농 배추 1012번 [백준]

TwoCastle9 2022. 8. 25. 15:40
반응형

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

 

1012번: 유기농 배추

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

www.acmicpc.net

 

 

유기농 배추는 dfs혹은 bfs로 간단하게 풀어낼 수 있는 문제이다.

배추가 존재하고 이전에 방문하지 않았던 좌표만을 재귀를 통해 진입하는게 코드의 핵심이다.

 

다만 흰배추잎벌레는 뭉쳐있는 배추를 한번에 처리가 가능하므로 처음 dfs함수로 진입할 때에만 cnt의 값을 1 증가시킨다.

 

#include<bits/stdc++.h>
#include<sys/types.h>

using namespace std;
#define endl '\n'
#define fast_io ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define rep(i, j) for(ll i=0;i<j;i++)

int m, n, k;
int matrix[50][50];
int visited[50][50];
int dx[] = {0, 1, -1, 0};
int dy[] = {1, 0, 0, -1};


void dfs(int x, int y) {
    visited[x][y] = true;
    rep(i, 4) {
        int x2 = x + dx[i], y2 = y + dy[i];
        if (x2 >= m || x2 < 0 || y2 >= n || y2 < 0)continue;
        if (matrix[x2][y2] == 1 && !visited[x2][y2]) {
            dfs(x2, y2);
        }
    }
}

void solve() {
    cin >> m >> n >> k;
    rep(i, k) {
        int x, y;
        cin >> x >> y;
        matrix[x][y] = 1;
    }//0, 1, 2
    int cnt = 0;
    rep(i, m) {
        rep(j, n) {
            if (matrix[i][j] == 1 && !visited[i][j]) {
                dfs(i, j);
                cnt++;
            }
        }
    }
    cout << cnt << endl;
    memset(matrix, 0, sizeof(matrix));
    memset(visited, 0, sizeof(visited));
}

int main() {

    fast_io;

    int t;
    cin >> t;
    rep(i, t)solve();
    return 0;
}
반응형

'알고리즘 > PS 문제' 카테고리의 다른 글

Integer List(AC) 5430번 [백준]  (0) 2022.08.27
Z 1074번 [백준]  (0) 2022.08.26
두 배열의 합 2143번 [백준]  (0) 2021.12.24
비숍 1799번 [백준]  (0) 2021.12.23
외판원 순회 2098번 [백준]  (0) 2021.12.22