본문 바로가기
PS/BOJ

[백준]1012. 유기농배추(c++)

by backend 개발자 지망생 2025. 2. 24.

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

2차원 배열에서 방문하지 않고 배추가 있는 좌표에서 시작하기

배추가 없는 곳은 피하면 된다.

 


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <limits.h>
#include <queue>
#include <set>
#include <math.h>
#include <stack>
#include <deque>
#include <tuple>

using namespace std;

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

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);


    int t;

    cin >> t;

    while (t--) {
        int m, n, k;

        int cnt = 0;

        cin >> m >> n >> k;

        vector<vector<int> > arr(n, vector<int>(m));
        vector<vector<int> > visited(n, vector<int>(m));
        queue<pair<int, int> > q;

        for (int i = 0; i < k; i++) {
            int tempX, tempY;
            cin >> tempX >> tempY;
            arr[tempY][tempX] = 1;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (!visited[i][j] && arr[i][j]) {
                    cnt++;
                    q.push({i, j});
                    visited[i][j] = 1;
                    while (!q.empty()) {
                        int y = q.front().first;
                        int x = q.front().second;
                        q.pop();

                        for (int l = 0; l < 4; l++) {
                            int ny = y + dy[l];
                            int nx = x + dx[l];
                            if (ny < 0 || ny >= n || nx < 0 || nx >= m) continue;
                            if (visited[ny][nx] || !arr[ny][nx]) continue;
                            q.push({ny, nx});
                            visited[ny][nx] = 1;
                        }
                    }
                }
            }
        }

        cout << cnt << '\n';
    }
    return 0;
}

'PS > BOJ' 카테고리의 다른 글

[백준] 10026. 적록색약(c++)  (0) 2025.03.02
[백준]5014. 스타트링크(c++)  (0) 2025.02.26
[백준] 1697. 숨바꼭질(c++)  (0) 2025.02.24
[백준] 4179. 불!(c++)  (0) 2025.02.24
[백준] 7576. 토마토(c++)  (0) 2025.02.24