Docsity

Breadth First Search (BFS) Algorithm Implementation in C++, Study Guides, Projects, Research of Advanced Computer Programming

Toggle sidebar
bg1
/*
Breadth First Search (BFS)
Assignment No 02
Language : C++
*/
#include<bits/stdc++.h>
using namespace std;
void bfs(int );
#define mx 99999
vector<int> g[mx];
int vis[mx];
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<int>q;
q.push(s);
while(!q.empty())
{
int x=q.front();
if(!vis[x])
pf2

Partial preview of the text

Download Breadth First Search (BFS) Algorithm Implementation in C++ and more Study Guides, Projects, Research Advanced Computer Programming in PDF only on Docsity!

Breadth First Search (BFS) Assignment No 02 Language : C++

#include<bits/stdc++.h> using namespace std;

void bfs(int );

#define mx 99999

vector g[mx]; int vis[mx];

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) { queueq;

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); } } }