Baekjoon

[#1260] DFS와 BFS

강람이 2020. 3. 31. 13:38
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
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <queue>
 
using namespace std;
int n, m, v;
vector<vector<int>> node(10001);
vector<bool> visit(10001false);
queue<int> q;
vector<bool> discover(10001false);
 
void dfs(int here) {
    visit[here] = true;
    printf("%d ", here);
 
    for (int i = 0; i < node[here].size(); i++) {
        int there = node[here][i];
        if (!visit[there]) {
            dfs(there);
        }
    }
}
 
int main() {
    
    
    scanf("%d %d %d"&n, &m, &v);
 
    for (int i = 1; i <= m; i++) {
        int a, b;
        scanf("%d %d"&a, &b);
 
        node[a].push_back(b);
        node[b].push_back(a);
    }
 
    for (int i = 1; i <= n; i++) {
        sort(node[i].begin(), node[i].end());
    }
    
    //dfs
    dfs(v);
    printf("\n");
 
    //bfs
    q.push(v);
    discover[v] = true;
    
    while (!q.empty()) {
        int here = q.front();  
        printf("%d ", here);
        q.pop();  //방문
 
        for (int i = 0; i < node[here].size(); i++) {
            int there = node[here][i];
            if (!discover[there]) {
                q.push(there);
                discover[there] = true;
            }
        }
    }
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

그래프 표현에 인접 리스트 사용

dfs는 재귀 또는 스택, bfs는 큐