알고리즘/BFS & DFS

[백준/BFS&DFS/C++] 2583번 영역 구하기

데메즈 2023. 3. 22. 11:03
728x90
반응형

 

문제는 여기!

#include <bits/stdc++.h>

using namespace std;

int N, M, K;
bool isVisited[101][101];
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
vector<int> answers;

void bfs(int a, int b){
    queue<pair<int, int>> q;
    q.push({a, b});
    isVisited[a][b] = true;
    int area = 1;

    while(!q.empty()){
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for(int i=0; i<4; i++){
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx<0 || nx>=M || ny<0 || ny>=N) continue;
            if(!isVisited[nx][ny]){
                isVisited[nx][ny] = true;
                q.push({nx, ny});
                area++;
            }
        }
    }
    answers.push_back(area);
}

void input() {
    cin >> M >> N >> K;
    for(int i=0; i<K; i++){
        int a, b, c, d;
        cin >> a >> b >> c >> d;
        for(int x=b; x<d; x++){
            for(int y=a; y<c; y++){
                isVisited[x][y] = true;
            }
        }
    }
}

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

    input();
    for(int i=0; i<M; i++){
        for(int j=0; j<N; j++){
            if(!isVisited[i][j]){
                bfs(i, j);
            }
        }
    }
    sort(answers.begin(), answers.end());
    cout << answers.size() << '\n';
    for(int i=0; i<answers.size(); i++){
        cout << answers[i] << ' ';
    }


    return 0;
}
728x90
반응형