bfs tree traversal code example
Example: bfs traversal code
#include
using namespace std;
#define ll long long int
#define ull unsigned long long int
void addedge(vectoradj[],int u,int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void print_list(vector adj[],int n)
{
for(int i=0;i" << ele << " \n";
}
}
}
void BFS(int v,int e,vectoradj[])
{
bool visited[e];
for(int i=0;iqueue;
visited[v]= true;
queue.push_back(v);
while (!queue.empty())
{
v = queue.front();
cout << v << " ";
queue.pop_front();
for(auto ele:adj[v])
{
if(!visited[ele])
{
visited[ele]= true;
queue.push_back(ele);
}
}
}
}
int main()
{
int n,e;
cin >> n >> e;
vector adj[n];
int u,v;
for(int i=0;i> u >> v;
addedge(adj,u,v);
}
print_list(adj,n);
BFS(v,e,adj);
return 0;
}