본문 바로가기
백준

[백준] 1260 - DFS와 BFS, C++

by 황인태(intaehwang) 2020. 1. 6.
반응형

https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.

www.acmicpc.net

 본 문제는 백준 1260 문제로 DFS와 BFS를 코딩할 줄 아는지 물어보는 문제다. DFS와 BFS를 구현할 줄 알면 쉬운 문제다.

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
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
 
using namespace std;
 
vector<int> v[1001];
bool chk[1001];
 
void dfs(int now) {
    chk[now] = true;
    printf("%d ", now);
    for (int i = 0; i < v[now].size(); i++) {
        int next = v[now][i];
        if (!chk[next]) dfs(next); 
    }
}
 
int main() {
    int n, m, start, a, b;
    scanf("%d %d %d"&n, &m, &start);
    // 간선 입력
    for (int i = 0; i < m; i++) {         
        scanf("%d %d"&a, &b);
        v[a].push_back(b);
        v[b].push_back(a);
    }
    // 조건) 정점 번호가 작은것을 먼저 방문한다.
    for (int i = 1; i <= n; i++) {
        sort(v[i].begin(), v[i].end());
    }
    dfs(start);
    printf("\n");
    // chk 초기화
    for (int i = 1; i <= n; i++) {
        chk[i] = false;
    }
    queue<int> q;
    q.push(start);
    chk[start] = true;
    while (!q.empty()) {
        int now = q.front();
        printf("%d", now);
        q.pop();
        for (int i = 0; i < v[now].size(); i++) {
            int next = v[now][i];
            if (!chk[next]) {
                chk[next] = true;
                q.push(next);
            }
        }
        if (!q.empty()) printf(" ");
    }
    return 0;
}
cs
반응형
Buy me a coffeeBuy me a coffee

댓글