BFS
BFS
h>
#include<stdlib.h>
#define MAX 20
typedef struct Q
{
int data[MAX];
int R,F;
}Q;
int main()
{
int i;
cout<<"\n***create a node****";
readgraph();
cout<<"\n***BFS***";
cout<<"\nStarting Node No. : ";
cin>>i;
BFS(i);
return 0;
}
void BFS(int v)
{
int w,i;
Q q;
node *p;
q.R=q.F=-1; //initialise
for(i=1;i<=n;i++)
discovered[i]=0;
enqueue(&q,v);
int l=0;
layer[v]=l;
parent[v]=-1;
cout<<"\nVisit\t"<<v;
cout<<"\tand its parent is none and layer is "<<layer[v];
discovered[v]=1;
while(!empty(&q))
{
v=dequeue(&q);
//insert all undiscovered,adjacent vertices of v into queue
for(p=G[v];p!=NULL;p=p->next)
{
w=p->vertex;
if(discovered[w]==0)
{
parent[w]=v;
layer[w]=layer[parent[w]]+1;
enqueue(&q,w);
discovered[w]=1;
cout<<"\nvisit\t"<<w;
cout<<"\n Parent of "<<w<<"is "<<parent[w];
cout<<"\t and its layer is "<<layer[w];
}
}
}
}
void readgraph()
{ int i,vi,vj,no_of_edges;
cout<<"\nEnter no. of vertices :";
cin>>n;
//initialise G[] with NULL
for(i=0;i<n;i++)
G[i]=NULL;
//read edges and insert them in G[]
cout<<"\nEnter no of edges :";
cin>>no_of_edges;
for(i=0;i<no_of_edges;i++)
{
cout<<"\nEnter an edge (u,v) :";
cin>>vi>>vj;
insert(vi,vj);
insert(vj,vi);
}
}