[백준 알고리즘]/[C++]

백준 2583 영역 구하기 | BFS | C++

말하는펭귄 2021. 3. 11. 13:30
728x90
반응형

 

 

이번 포스팅은 백준 2583번 영역 구하기입니다.

아래 url를 클릭하시면 백준 사이트에서 문제를 볼 수 있습니다.

www.acmicpc.net/problem/2583

 

2583번: 영역 구하기

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

www.acmicpc.net

 

 

 

기본 알고리즘

BFS (너비 우선 탐색)

 

 

 

전체 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//백준2583 영역구하기                                                        
 
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
 
int M, N, K;
const int MAX = 101;
int map[MAX][MAX];
bool visited[MAX][MAX];
queue<pair<intint>> q;
int dy[] = { 0,0,-1,1 };
int dx[] = { -1,1,0,0 };
vector<int> v;
int s = 1;
 
void BFS(int y, int x) {
    visited[y][x] = true;
    q.push(make_pair(y, x));
 
    while (!q.empty()) {
        y = q.front().first;
        x = q.front().second;
        q.pop();
 
        for (int i = 0; i < 4; i++) {
            int ny = y + dy[i];
            int nx = x + dx[i];
 
            if (ny<0 || nx<0 || ny>=|| nx>=N)
                continue;
            if (map[ny][nx] == 0 && !visited[ny][nx]) {
                visited[ny][nx] = true;
                q.push(make_pair(ny, nx));
                s++;
            }
        }
    }
}
 
int main() {
    cin >> M >> N >> K;
 
    int x1, y1, x2, y2;
    while (K--) {
        cin >> x1 >> y1 >> x2 >> y2;
 
        for (int i = M-y2; i < M-y1; i++) {
            for (int j = x1; j < x2; j++) {
                map[i][j] = 1;
            }
        }
    }
 
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++) {
            if (map[i][j] == 0 && !visited[i][j]) {
                BFS(i, j);
                v.push_back(s);
                s = 1;
            }
        }
    }
 
    sort(v.begin(), v.end());
 
    cout << v.size() << endl;
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
 
}
cs

 

 

 

 

 

728x90
반응형