ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 그래프_백준_연결 요소_11724
    Algorithm 2018. 8. 30. 21:07

    Connected Component

    아래의 그림과 같이 나누어진 각각의 그래프를 연결 요소라고 한다. 아래 그래프는 총 2개의 연결 요소로 이루어져 있다. 연결 요소를 구하는 것은 dfS나 BFS 탐색을 이용해서 구할 수 있다. 시작점을 for문으로 이동하는 동시에 탐색 진행.


    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
    #include <iostream>
    #include <algorithm>
    #include <stack>
    #include <vector>
    using namespace std;
     
    vector <int> a[1001];
    bool check[1001];
     
    void dfs(int x) {
        check[x] = true;
        for (int i = 0; i < a[x].size(); i++) {
            int next = a[x][i];
            if (check[next] == false) {
                check[next] = true;
                dfs(next);
            }
        }
    }
     
    int main() {
        int n, e, u, v;
        int result = 0;
        scanf("%d %d"&n, &e);
     
        for (int i = 1; i <= e; i++) {
            scanf("%d %d"&u, &v);
     
            a[u].push_back(v);
            a[v].push_back(u);
        }
     
        for (int i = 1; i <= n; i++) {
            sort(a[i].begin(), a[i].end());
        }
     
        for (int i = 1; i <= n; i++) {
            if (check[i] == false) {
                dfs(i);
                result++;
            }
        }
     
        printf("%d\n", result);
        return 0;
    }
    cs




    'Algorithm' 카테고리의 다른 글

    그래프_백준_순열 사이클_10451  (0) 2018.08.31
    그래프_백준_이분 그래프_1707  (0) 2018.08.31
    그래프_백준_DFS와 BFS_1260  (0) 2018.08.30
    그래프_백준_그래프의 탐색  (0) 2018.08.23
    그래프_백준_이론  (0) 2018.08.22
Designed by Tistory.