Blog Content

    티스토리 뷰

    1260번 백준(Baekjoon)

    <문제>

    그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.

    <정답 코드>

    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
    75
    76
    77
    #include <iostream>
    #include <cstdio>
    #include <vector>
    #include <queue>
    #include <algorithm>
     
    using namespace std;
     
    int check[1001];
    int N, M, V;
    vector<int> vc[1001];
    queue<int> q;
    int from, to;
     
    bool dfs(int pos)
    {
        printf("%d ", pos);
        check[pos] = 1;
        for(int i=0; i<vc[pos].size(); i++)
        {
            int next = vc[pos][i];
            if(check[next] == 0 && !dfs(next))
                return false;
        }
        return true;
    }
     
    bool bfs(int pos)
    {
        printf("%d ", q.front());
        check[q.front()] = 1;
        while (!q.empty())
        {
            // 방문을 시작하는 정점을 확인
            int front = q.front();
            q.pop();
     
            // 그 정점과 연결되어있는 정점을 확인
            for (int i = 0; i < vc[front].size(); i++)
            {
                if (check[vc[front][i]] == 0)
                {
                    q.push(vc[front][i]);
                    printf("%d ", vc[front][i]);
                    check[vc[front][i]] = 1;
                }
            }
        }
     
        return true;
    }
     
    int main()
    {
        scanf("%d%d%d"&N, &M, &V);
     
        for(int i=0; i<M; i++)
        {
            scanf("%d%d"&from, &to); 
            vc[from].push_back(to);
            vc[to].push_back(from);
        }
     
        for(int i=0; i<N; i++)
            sort(vc[i].begin(), vc[i].end());
     
        dfs(V);
     
        printf("\n");
     
        fill(check, check+10010); // check를 0으로 초기화
     
        q.push(V);
        bfs(V);
     
        return 0;
    }
    cs


    'C++ 문제풀이' 카테고리의 다른 글

    1697번 백준(Baekjoon)  (0) 2018.09.24
    1929번 백준(Baekjoon)  (0) 2018.09.07
    1157번 백준(Baekjoon)  (0) 2018.09.06
    8958번 백준(Baekjoon)  (0) 2018.09.05
    1152번 백준(Baekjoon)  (0) 2018.09.04

    Comments