알고리즘
백준 1260 DFS와 BFS
중국고대사
2019. 4. 5. 02:14
c++로 graph를 구현하는 것은 vector의 배열을 이용하면 되므로 편하다.
그리고 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
53
54
55
56
57
58
59
60
61
62
63
64
65
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
int v, e, s;
bool check[10000];
vector<int> g[10000];
void dfs(int x) {
check[x] = true;
printf("%d ", x);
for (int i = 0; i < g[x].size(); i++) {
int next = g[x][i];
if (!check[next])dfs(next);
}
}
void bfs(int x) {
//memset을 쓰기 위해서는 cstring 헤더를 include 해야 한다.
//check를 dfs에서 썼기 때문에 초기화 한다.
memset(check, false, sizeof(check));
queue<int> q;
//처음 넣는 node를 check해야 한다.
check[x] = true;
q.push(x);
while (!q.empty()) {
int current = q.front();
q.pop();
printf("%d ", current);
for (int i = 0; i < g[current].size(); i++) {
int next = g[current][i];
if (!check[next]) {
check[next] = true;
q.push(next);
}
}
}
}
int main(int argc, char** argv) {
cin >> v >> e >> s;
for (int i = 0; i < e; i++) {
int from, to;
cin >> from >> to;
//양방향으로 넣는 거 까먹지 않기
g[from].push_back(to);
g[to].push_back(from);
}
//문제에서 오름차순이라 했으니까 sorting 해준다.
for (int i = 1; i <= v; i++) {
sort(g[i].begin(), g[i].end());
}
dfs(s);
printf("\n");
bfs(s);
return 0;
}
|
cs |