본문 바로가기
알고리즘 문제 풀이

[백준] - 유기농 배추 - 복습

by pinok1o 2021. 1. 31.

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

DFS

#include <iostream>

using namespace std;

int M;
int N;

void dfs(int x, int y, int input[][52], int check[][52])
{
    check[x][y] = 1;

    int dx[] = { 0, 0, 1, -1 };
    int dy[] = { 1, -1, 0, 0 };

    for (int i = 0; i < 4; i++)
    {
        int nx = x + dx[i];
        int ny = y + dy[i];
        if (nx >= 0 && ny >= 0 && nx < M && ny < N) {
            if (!check[nx][ny] && input[nx][ny] == 1) {
                dfs(nx, ny, input, check);
            }
        }
    }
}

int main()
{
    int T;

    cin >> T;

    for (int i = 0; i < T; i++)
    {

        int K;
        cin >> M >> N >> K;

        int input[52][52] = { 0, };
        int check[52][52] = { 0, };

        //plant cabbage
        for (int j = 0; j < K; j++)
        {
            int x;
            int y;
            cin >> x >> y;

            input[x][y] = 1;
        }
        int count = 0;
        for (int l = 0; l < M; l++)
        {
            for (int p = 0; p < N; p++)
            {
                if (!check[l][p] && input[l][p]) {
                    dfs(l, p, input, check);
                    count++;
                }
            }
        }
        cout << count << endl;
    }
} 

댓글