

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Breadth First Search (BFS) Assignment No 02 Language : C++
#include<bits/stdc++.h> using namespace std;
void bfs(int );
#define mx 99999
vector
int main(void) { int n , e , a , b ;
cout<<"Enter how many nodes : "; cin>>n;
cout<<endl<<"Enter how many edges : "; cin>>e;
cout<<endl<<"Enter the node to node relations : "<<endl; for(int i=0 ; i<e ; i++) { cin>>a>>b; g[a].push_back(b); g[b].push_back(a); }
cout<<endl<<"Enter the root : "; cin>>a;
cout<<endl<<"BFS result : "<<endl; bfs(a);
return 0; }
void bfs(int s) { queue
q.push(s);
while(!q.empty()) { int x=q.front(); if(!vis[x])
cout<<x<<" ";
vis[x] = 1;
q.pop();
for(int i=0 ; i<g[x].size() ; i++) { int v=g[x][i];
if(!vis[v]) q.push(v); } } }