-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01260_DFSandBFS.cpp
More file actions
71 lines (65 loc) · 1.18 KB
/
01260_DFSandBFS.cpp
File metadata and controls
71 lines (65 loc) · 1.18 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
#include <iostream>
#include <queue>
using namespace std;
int n, m, v;
int graph1[1001][1001];
int graph2[1001][1001];
queue<int> q;
void input()
{
cin >> n >> m >> v;
while (m--)
{
int s, e;
cin >> s >> e;
graph1[s][e] = 1;
graph2[s][e] = 1;
graph1[e][s] = 1;
graph2[e][s] = 1;
}
}
void DFS(int node)
{
cout << node << ' ';
graph1[node][node] = 1;
for (int i = 1; i <= n; i++)
{
if (node != i && graph1[node][i] && !graph1[i][i])
{
graph1[node][i] = 0;
graph1[i][node] = 0;
DFS(i);
}
}
}
void BFS(int node)
{
q.push(node);
while (!q.empty())
{
node = q.front();
cout << node << ' ';
for (int i = 1; i <= n; i++)
{
if (graph2[node][i] && !graph2[i][i])
{
q.push(i);
graph2[node][i] = 0;
graph2[i][node] = 0;
graph2[i][i] = 1;
}
}
q.pop();
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
input();
DFS(v);
cout << '\n';
BFS(v);
return 0;
}