문제 링크입니다 https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
www.acmicpc.net
[소스코드]
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
|
// [DFS & BFS] 백준(1260) : DFS와 BFS
#include<algorithm>
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
vector <int> graph[1010];
int n, m, v, a, b;
bool visit_dfs[1010], visit_bfs[1010];
// node부터 dfs로 그래프를 순회한 결과를 출력하는 함수
void dfs(int node) {
printf("%d ", node);
visit_dfs[node] = true;
for (int i = 0; i < graph[node].size(); i++) {
int next = graph[node][i];
if (!visit_dfs[next]) dfs(next);
}
}
// node부터 bfs로 그래프를 순회한 결과를 출력하는 함수
void bfs(int node) {
queue <int> q;
q.push(node);
visit_bfs[node] = true;
while (!q.empty()) {
int cur = q.front();
q.pop();
printf("%d ", cur);
for (int i = 0; i < graph[cur].size(); i++) {
int next = graph[cur][i];
if (!visit_bfs[next]) {
visit_bfs[next] = true;
q.push(next);
}
}
}
}
int main(void) {
scanf("%d%d%d", &n, &m, &v);
for (int i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
graph[a].push_back(b);
graph[b].push_back(a);
}
// 정점 번호가 작은 것부터 출력하기 위해 정렬
for (int i = 0; i < n; i++) {
sort(graph[i].begin(), graph[i].end());
}
dfs(v);
printf("\n");
bfs(v);
return 0;
}
|
cs |

'알고리즘 > BaekJoon' 카테고리의 다른 글
백준 14501 : 퇴사 (0) | 2020.02.20 |
---|---|
백준 11403 : 경로 찾기 (0) | 2020.02.19 |
백준 1996 : 프린터 큐 (0) | 2020.02.19 |
백준 14500 : 테트로미노 (0) | 2020.02.18 |
백준 14889 : 스타트와 링크 (0) | 2020.02.18 |