ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 그래프_백준_DFS와 BFS_1260
    Algorithm 2018. 8. 30. 13:12


    구현

    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
    #include <iostream>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <vector>
    #include<cstring>
    using namespace std;
     
    vector <int> a[1001];
    bool check[1001];
     
    void dfs(int x) {
        check[x] = true;
        printf("%d ", x);
        for (int i = 0; i < a[x].size(); i++) {
            int next = a[x][i];
            if (check[next] == false) {
                check[next] = true;
                dfs(next);
            }
        }
    }
     
    void bfs(int start) {
        memset(check, falsesizeof(check));
        queue <int> q;
        check[start] = true;
        q.push(start);
     
        while (!q.empty()) {
            int top = q.front();
            q.pop();
            printf("%d ", top);
     
            for (int i = 0; i < a[top].size(); i++) {
                int tmp = a[top][i];
                if (check[tmp] == false) {
                    q.push(tmp);
                    check[tmp] = true;
                }
            }
        }
    }
     
    int main() {
        int n, e, start;
        int u, v;
        scanf("%d %d %d"&n, &e, &start);
     
        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());
        }
     
        dfs(start);
        printf("\n");
        bfs(start);
        printf("\n");
    }
    cs



    'Algorithm' 카테고리의 다른 글

    그래프_백준_이분 그래프_1707  (0) 2018.08.31
    그래프_백준_연결 요소_11724  (0) 2018.08.30
    그래프_백준_그래프의 탐색  (0) 2018.08.23
    그래프_백준_이론  (0) 2018.08.22
    정렬_백준_K번째 수_11004  (0) 2018.08.21
Designed by Tistory.