본문 바로가기

Algorithm/BFS

(C++) - 백준(BOJ) 1260번 : DFS와 BFS 답

반응형

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

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

 

기본적인 DFS와 BFS를 구현하는 문제였습니다.

풀이방법 :

DFS : 정점 i에서 시작하여 그와 연결된 정점을 또다른 시작점으로 하는 재귀함수로 구현하였습니다.

BFS : 정점 i에서 시작하여 그와 연결된 모든 정점을 그 노드 번호가 낮은 노드를 최우선순위로 탐방하도록 queue를 이용하여 작성하였습니다.

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
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
vector <int> graph[10001];
int ck[1001];
int n,m,s;
 
void bfs(int i){
    ck[i] = 1;
    queue <int> q;
    q.push(i);
    while(!q.empty()){
        int x = q.front();
        q.pop();
        cout << x << ' ';
        for(int j = 0; j < graph[x].size(); j++){
            int next = graph[x][j];
            if(!ck[next]){
                q.push(next);
                ck[next] = 1;
            }
        }
    }
}
void dfs(int i){
    ck[i] = 1;
    cout << i << ' ';
    for(int j = 0; j<graph[i].size(); j++){
        int next = graph[i][j];
        if(!ck[next]) dfs(next);
    }
}
 
int main(){
    cin >> n >> m >> s;
    for(int i = 0; i<m; i++){
        int u,v;
        cin >> u >> v;
        graph[u].push_back(v);
        graph[v].push_back(u);
    }
    for(int i = 1; i<=n; i++){
        sort(graph[i].begin(),graph[i].end());
    }
    dfs(s);
    cout << '\n';
    memset(ck,0,sizeof(ck));
    bfs(s);
}