-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1260_DFS,BFS.cpp
61 lines (54 loc) · 960 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
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
int arr[1001][1001];
bool check[1001];
int n, m, v;
void dfs(int v)
{
check[v] = true;
printf("%d ", v);
for (int i = 1; i <= n; i++)
{
if (arr[v][i] == 1 && !check[i])
{
dfs(i);
}
}
}
void bfs(int v)
{
queue<int> q;
check[v] = true;
q.push(v);
while (!q.empty())
{
int x = q.front();
q.pop();
printf("%d ", x);
for (int i = 1; i <= n; i++)
{
if (arr[x][i] == 1 && !check[i])
{
check[i] = true;
q.push(i);
}
}
}
}
int main()
{
scanf("%d %d %d", &n, &m, &v);
for (int i = 0; i < m; i++)
{
int x, y;
scanf("%d %d", &x, &y);
arr[x][y] = true;
}
dfs(v);
printf("\n");
memset(check, false, sizeof(check));
bfs(v);
return 0;
}