PROGRAM TO IMPLEMENT BREADTH-FIRST-SEARCH


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<alloc.h>
#define max 100
void bfs(int n,int s);
void enqueue(int q[],int m);
int dequeue(int q[]);
int color[max];
int d[max];
int pi[max];
typedef struct vert* ver;
struct vert
{
int ident;
ver next;
}cor;
ver adj_list[max];
void main()
{
int n,i,j,k,s,u;
ver temp,prev;
clrscr();
printf("Enter no. of nodes");
scanf("%d",&n);
for(i=0;i<=n;i++)
adj_list[i]='\0' ;
for(i=1;i<=n;i++)
{
prev=NULL;
printf("enter no. of vertex connected to %d",i);
scanf("%d",&j);
for(k=0;k<j;k++)
{
temp=(ver)malloc(sizeof(cor));
temp->next=NULL;
printf("Enter vertex no. connected to vertex %d",i);
scanf("%d",&temp->ident);
if(prev==NULL)
adj_list[i]=temp;
else
prev->next=temp;
prev=temp;
}
}
printf("\n enter the strating point of graph");
scanf("%d",&s);
bfs(n,s);
for(i=1;i<=n;i++)
{
printf("\n the distance from source(%d)to %d is %d",s,i,d[i]);
printf("\n the previous vertex of %d is %d",i,pi[i]) ;
}
getch();
}
void bfs(int n,int s)
{
int i,v,q[max],u;
ver temp;
for(i=1;i<=n;i++)
{
if(i==s)
continue;
color[i]=0;
d[i]=32767;
pi[i]=NULL;
}
color[s]=1;
d[s]=0;
pi[s]=NULL;
for(i=0;i<=n;i++)
q[i]='\0' ;
enqueue(q,s);
while(q[0]!='\0')
{
u=dequeue(q);
temp=adj_list[u];
while(temp!=NULL)
{
v=temp->ident;
if(color[v]==0)
{
color[v]=1;
d[v]=d[u]+1;
pi[v]=u;
enqueue(q,v);
}
temp=temp->next;
}
color[u]=2;
}
}
void enqueue(int q[max],int m)
{
int i=0;
while(q[i]!='\0')
{
i++;
}
q[i]=m;
}
int dequeue(int q[max])
{
int i=0,ret;
ret=q[i];
while(q[i]!='\0')
{
q[i]=q[i+1];
i++;
}
return ret;
}

Comments

Popular posts from this blog

REFLECTION OF A TRIANGLE (COMPUTER GRAPHICS)