-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS_DFS.cpp
More file actions
114 lines (98 loc) · 1.91 KB
/
BFS_DFS.cpp
File metadata and controls
114 lines (98 loc) · 1.91 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include<stack>
typedef std::vector<std::vector<int>> Graph;
//bool visit[1010] = { 0, };
//std::vector<std::vector<int>> G;
//void DFS(const G& G, int s)
//{
// std::vector<bool> visit(G.size(), false);
//
// DFS_VISIT(G, s, visit);
//}
//
//
//void DFS_VISIT(G &G, int x, std::vector<bool> &visit)
//{
// bool visit[1010] = { 0, };
// visit[x] = true;
// std::cout << x << ' '; // 순회출력
//
// for (std::size_t i = 0; i < G[x].size(); i++)
// {
// int next = G[x][i];
// if (visit[next] != true)
// DFS_VISIT( G, next);
// }
//}
void DFS(const Graph &G, int x)
{
std::vector<bool> visit(G.size(), false);
visit[x] = true;
std::stack<int> sub_s;
sub_s.push(x);
//std::cout << sub_s.top() << ' '; // 순회출력
while (!sub_s.empty())
{
int y = sub_s.top();
std::size_t G_size = G[y].size();
for (std::size_t i = 0; i < G_size; i++)
{
int next = G[y][i];
if (visit[next] != true)
{
visit[next] = true;
sub_s.push(next);
//std::cout << sub_s.top() << ' '; // 순회출력
i = -1;
y = sub_s.top();
G_size = G[y].size();
}
}
sub_s.pop();
}
}
void BFS(const Graph &G, int x)
{
std::queue<int> Q;
Q.push(x);
std::vector<bool> visit(G.size(), false);
visit[x] = true;
while (!Q.empty())
{
int here = Q.front();
Q.pop();
std::cout << here << ' ';// 순회 출력
std::size_t G_size = G[here].size();
for (std::size_t i = 0; i < G_size; i++)
{
int next = G[here][i];
if (visit[next] != true)
{
visit[next] = true;
Q.push(next);
}
}
}
}
int main()
{
int n, m, s;
std::cin >> n >> m >> s;
Graph G;
G.resize(n + 1);
for (int i = 0; i < m; i++)
{
int u, v;
std::cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
for (int i = 1; i <= n; i++) // 리스트 넘버순 정렬
std::sort(G[i].begin(), G[i].end());
DFS(G,s);
puts("");
BFS(G,s);
}