-
Notifications
You must be signed in to change notification settings - Fork 8
/
bfs.cpp
46 lines (45 loc) · 847 Bytes
/
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
#include<bits/stdc++.h>
using namespace std;
bool vis[1001];
vector<int> g[1001];
void bfs(int s,vector<int> adj[],bool vis[]);
int main()
{
int T;
cin>>T;
while(T--)
{
memset(g,0,sizeof g);
memset(vis,false,sizeof vis);
int N;
cin>>N;
for(int i=0;i<N;i++)
{
int u,v;
cin>>u>>v;
g[u].push_back(v);
}
bfs(1,g,vis);
cout<<endl;
}
}
void bfs(int s,vector<int> adj[],bool vis[])
{
queue<int> q;
q.push(s);
vis[s]=true;
while(!q.empty())
{
int p=q.front();
cout<<p<<" ";
q.pop();
for(int i=0;i<adj[p].size();i++)
{
if(vis[adj[p][i]]==false)
{
q.push(adj[p][i]);
vis[adj[p][i]]=true;
}
}
}
}