1012 - 유기농 배추

solution

code

#include <iostream>
#include <utility>
using namespace std;

void dfs(pair<int, bool> arr[], int N, int M, int i)
{
    arr[i].second = true;
    if(i%M != 0)
        if(arr[i-1].first == 1 && !arr[i-1].second)
            dfs(arr, N, M, i-1);
    if(i%M != M-1)
        if(arr[i+1].first == 1 && !arr[i+1].second)
            dfs(arr, N, M, i+1);
    if(i-M >= 0)
        if(arr[i-M].first == 1 && !arr[i-M].second)
            dfs(arr, N, M, i-M);
    if(i+M < N*M)
        if(arr[i+M].first == 1 && !arr[i+M].second)
            dfs(arr, N, M, i+M); 
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    int testC;
    cin >> testC;
    int N, M, K;
    int x, y;
    int ans = 0;
    for(int c = 0; c < testC; c++)
    {
        cin >> M >> N >> K;
        pair<int, bool> * arr = new pair<int, bool>[N*M];
        ans = 0;
        for(int i = 0; i < N*M; i++)
        {
            arr[i].first = 0;
            arr[i].second = false;
        }
        for(int i = 0; i < K; i++)
        {
            cin >> x >> y;
            arr[M*y+x].first = 1;
        }
        for(int i = 0; i < N*M; i++)
        {
            if(arr[i].first == 1)
                if(!arr[i].second)
                {
                    dfs(arr, N, M, i);
                    ans++;
                }
        }
        cout << ans << endl;
    }
    return 0;
}

ref

1012번: 유기농 배추