-
Notifications
You must be signed in to change notification settings - Fork 3
/
BFS Graph.cpp
79 lines (64 loc) · 1.22 KB
/
BFS Graph.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
#include <bits/stdc++.h>
using namespace std;
#define sf scanf
#define pf printf
#define pb push_back
#define MAX 10000
vector <int> edges[MAX+1],cost[MAX+1];
bool vis[MAX+1];
int lv[MAX+1];
void BFS (int s, int n)
{
int u,v,i,l;
vector <int> G;
queue <int> q;
q.push(s);
vis[s] = true;
lv[s] = 0;
while (!q.empty())
{
u = q.front();
G.pb(u);
q.pop();
l = edges[u].size();
for (i=0; i<l; i++)
{
v = edges[u][i];
if (!vis[v])
{
q.push(v);
vis[v] = true;
lv[v] = lv[u]+1;
}
}
}
l = G.size();
pf ("BFS Graph : ");
for (i=0; i<l; i++)
{
pf ("%d",G[i]);
if (i == l-1)
pf ("\n");
else
pf (" ");
}
}
int main ()
{
int n,e,i,x,y,s;
sf ("%d %d",&n,&e);
for (i=1; i<=e; i++)
{
sf ("%d %d",&x,&y);
if (x == y)
edges[x].pb(y);
else
{
edges[x].pb(y);
edges[y].pb(x);
}
}
sf ("%d",&s);
BFS (s,n);
return 0;
}