-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1260 DFS와 BFS.cpp
71 lines (61 loc) · 860 Bytes
/
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
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int MAX = 1001;
vector<int> adj[MAX];
queue<int> Q;
bool visit[MAX];
void dfs(int x)
{
visit[x] = true;
printf("%d ", x);
for (int y : adj[x])
{
if (!visit[y])
dfs(y);
}
}
void bfs(int sx)
{
Q.push(sx);
visit[sx] = true;
while (!Q.empty())
{
int x = Q.front();
Q.pop();
printf("%d ", x);
for (int y : adj[x])
{
if (!visit[y])
{
Q.push(y);
visit[y] = true;
}
}
}
}
int main()
{
int n, m, v;
scanf("%d %d %d", &n, &m, &v);
while (m--)
{
int s, e;
scanf("%d %d", &s, &e);
adj[s].push_back(e);
adj[e].push_back(s);
}
for (int i = 1; i <= n; i++)
{
sort(adj[i].begin(), adj[i].end());
}
dfs(v);
puts("");
memset(visit, 0, sizeof(visit));
bfs(v);
puts("");
return 0;
}