-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfs&bfs.cpp
58 lines (56 loc) · 962 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
56
57
58
#include <iostream>
#include <queue>
#include <stack>
#include <cstring>
using namespace std;
int node[1000][1000];
int n, m, v, a, b;
queue<int> q;
stack<int> s;
void bfs() {
int k, visited[1000];
memset(visited, 0, sizeof(visited));
q.push(v);
visited[v] = 1;
while (!q.empty()) {
k = q.front();
q.pop();
cout << k << ' ';
for (int i = 1; i <= n; i++) {
if (node[k][i] == 1 && visited[i] != 1) {
q.push(i);
visited[i] = 1;
}
}
}
cout << endl;
}
void dfs() {
int k, visited[1000];
memset(visited, 0, sizeof(visited));
s.push(v);
visited[v] = 1;
cout << v << ' ';
while (!s.empty()) {
for (int i = 1; i <= n; i++) {
if (node[s.top()][i] == 1 && visited[i] != 1) {
s.push(i);
cout << i << ' ';
visited[i] = 1;
i = 0;
}
}
s.pop();
}
cout << endl;
}
int main() {
cin >> n >> m >> v;
for (int i = 0; i<m; i++) {
cin >> a >> b;
//ÀÎÁ¢³ëµå
node[a][b] = node[b][a] = 1;
}
dfs();
bfs();
}