YoonWould!!

[BFS,DFS] 2667번 단지번호붙이기 본문

<SW>/알고리즘 + 자료구조

[BFS,DFS] 2667번 단지번호붙이기

Hading 2018. 10. 8. 01:17
728x90


URL : https://www.acmicpc.net/problem/2667


BFS와 DFS 참고 문제집 : https://www.acmicpc.net/workbook/view/2096

 






※이 문제 어떻게 풀지?


1. BFS와 Queue를 이용하여 단지 크기를 구하고자 했습니다.

2. mark를 이용하여 영역 표기 


※필요 역량 정리하기!!!※

1. pair, make_pair 함수를 사용할 때 => #include<utility>를 사용해 주자!!

 - 백준에서는 C++ 컴파일 에러가 나기 때문... 시험장가서도 똑같겠죠...

2. 결국 BFS...!!  밑에 소스는 <BFS + Queue>

3. sort함수에 대해서 알고 가자 => #include<algorithm>

 - sort( [배열] , [정렬할 배열 크기]);

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
#include<iostream>
#include<vector>
#include<queue> // queue
#include<utility> // pair, make_pair
#include<cstdio>
#include<algorithm>
using namespace std;
 
int n;
int map[26][26];
int visit[26][26];
int dan[26];
const int dx[] = { -1,1,0,0 };
const int dy[] = { 0,0,1,-1 };
 
void bfs(int startx, int starty,int mark) {
    queue<pair<intint> > q;
    q.push(make_pair(startx, starty));
    map[startx][starty] = mark;
    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 (map[nx][ny] == 1 && nx >= 0 && nx < n && ny >= 0 && ny < n) {
                /*
                반복문 기반 bfs
                q.push(make_pair(nx, ny));
                map[nx][ny] = 2;
                */
                //재귀함수 기반 bfs
                bfs(nx, ny,mark);
            }
        }
    }
}
 
int main() {
    cin >> n;
    int cnt = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf_s("%1d"&map[i][j]);
        }
    }
 
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (map[i][j] == 1) {
                bfs(i, j,cnt + 2 );
                cnt++;
            }
        }
    }
 
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (map[i][j] == 0continue;
 
            dan[map[i][j] - 2]++;
        }
    }
 
    sort(dan, dan + cnt);
    cout << cnt << endl;
    for (int i = 0; i < cnt; i++) {
        cout << dan[i] << endl;
    }
    return 0;
}
cs


728x90