forked from Dev-XYS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Breadth-First-Search.cpp
82 lines (64 loc) · 927 Bytes
/
Breadth-First-Search.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <cstdio>
#define VERTEX_COUNT 100000
#define EDGE_COUNT 100000
using namespace std;
struct vertex
{
int first_edge;
bool vis;
}V[VERTEX_COUNT];
struct edge
{
int endp, next;
}E[EDGE_COUNT];
int ec = 1;
int Q[VERTEX_COUNT];
int hp = 0, tp = 0;
void enqueue(int x)
{
Q[tp++] = x;
}
int dequeue()
{
return Q[hp++];
}
bool queue_empty()
{
return hp == tp;
}
void add_edge(int u, int v)
{
E[ec].next = V[u].first_edge;
V[u].first_edge = ec;
E[ec].endp = v;
ec++;
}
void BFS()
{
while (!queue_empty())
{
int u = dequeue();
for (int cur = V[u].first_edge; cur != 0; cur = E[cur].next)
{
if (V[E[cur].endp].vis == false)
{
V[E[cur].endp].vis = true;
enqueue(E[cur].endp);
}
}
}
}
int main()
{
int ivc, iec;
scanf("%d%d", &ivc, &iec);
for (int i = 0; i < iec; i++)
{
int u, v;
scanf("%d%d", &u, &v);
add_edge(u, v);
}
enqueue(1);
BFS();
return 0;
}