-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS와 BFS.cpp
55 lines (50 loc) · 858 Bytes
/
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
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int N, M, V;
vector<vector<int>>arr;
vector<bool>vis;
queue<int>q;
void DFS(int idx = V) {
cout << idx << ' ';
for (int i = 0; i < N+1; i++) {
if (arr[idx][i] && !vis[i]) {
vis[i] = 1;
DFS(i);
}
}
}
void BFS(int idx = V) {
q.push(idx);
vis[idx] = 1;
while (!q.empty()) {
cout << q.front() << ' ';
idx = q.front();
q.pop();
for (int i = 0; i < N+1; i++) {
if (arr[idx][i] && !vis[i]) {
vis[i] = 1;
q.push(i);
}
}
}
}
int main() {
cin >> N >> M >> V;
arr.resize(N + 1, vector<int>(N + 1, 0));
vis.resize(N + 1, 0);
for (int i = 0; i < N+1; i++) {
int from, to;
cin >> from >> to;
arr[from][to] = 1;
arr[to][from] = 1;
}
vis[V] = 1;
DFS();
cout << '\n';
fill(vis.begin(), vis.end(), 0);
BFS();
cout << '\n';
return 0;
}