출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

백준 2583 영역 구하기(bfs)

알고리즘

by 장동균 2020. 7. 27. 00:16

본문

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

 

2583번: 영역 구하기

첫째 줄에 M과 N, 그리고 K가 빈칸을 사이에 두고 차례로 주어진다. M, N, K는 모두 100 이하의 자연수이다. 둘째 줄부터 K개의 줄에는 한 줄에 하나씩 직사각형의 왼쪽 아래 꼭짓점의 x, y좌표값과 오

www.acmicpc.net

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;
const int MAX = 100;
int M, N, K;
bool visited[MAX][MAX];
int cnt;
typedef struct
{
    int x, y;
} Dir;
Dir Dirmove[4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int domain;
vector<int> answer;

void bfs(int x, int y)
{
    domain++;
    queue<pair<int, int>> q;
    q.push(make_pair(x, y));
    visited[x][y] = true;
    while (!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            int nextX = x + Dirmove[i].x;
            int nextY = y + Dirmove[i].y;
            if (0 <= nextX && nextX < M && 0 <= nextY && nextY < N && !visited[nextX][nextY])
                bfs(nextX, nextY);
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cin >> M >> N >> K;
    for (int i = 0; i < K; i++)
    {
        int x1, y1, x2, y2;
        cin >> y1 >> x1 >> y2 >> x2; //도형을 위아래로 뒤집는다 생각.
        for (int i = x1; i < x2; i++)
            for (int j = y1; j < y2; j++)
                visited[i][j] = true;
    }
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (!visited[i][j])
            {
                cnt++;
                bfs(i, j);
                answer.push_back(domain);
            }
            domain = 0;
        }
    }
    cout << cnt << "\n";
    sort(answer.begin(), answer.end());
    for (int i = 0; i < answer.size(); i++)
        cout << answer[i] << " ";
}

dfs 공부 꽤 햇으니 여태껏 풀엇던 문제들을 싹 다 bfs로도 푸러본다

관련글 더보기

댓글 영역