-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1260_DFS와BFS.cpp
72 lines (60 loc) · 1.01 KB
/
1260_DFS와BFS.cpp
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
69
70
71
72
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <memory.h>
#define ll long long
using namespace std;
bool visited[10001];
vector<int> adj[10001];
queue<int> q;
int N, M, V;
void bfs(int now)
{
visited[now] = 1;
q.push(now);
while (!q.empty()) {
int n = q.front();
q.pop();
cout << n << " ";
for (int i = 0; i < adj[n].size(); i++) {
int next = adj[n][i];
if (!visited[next]) {
visited[next] = 1;
q.push(next);
}
}
}
}
void dfs(int now)
{
visited[now] = 1;
cout << now << " ";
for (int i = 0; i < adj[now].size(); i++)
{
if (!visited[adj[now][i]])
{
dfs(adj[now][i]);
}
}
}
int main()
{
int a, b;
cin >> N >> M >> V;
for (int i = 0; i < M; i++) {
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for (int index = 0; index <= N; index++)
{
if (adj[index].size() > 1) sort(adj[index].begin(), adj[index].end());
}
dfs(V);
memset(visited, 0, 10001 * sizeof(bool));
cout << endl;
bfs(V);
return 0;
}