Friday, January 9, 2015

Graph and BFS Traversing in C

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
char data;
int status;
struct node *next;
struct link *adj;
}*start,*p,*q;
struct link
{
char nextlink;
struct node *next;
struct link *adj;
}*k,*l;
void create();
void show();
void bfs();
void main()
{
int i=0;
create();
while(i<3)
{
if(i==1)
{
show();
}
else if(i==2)
{
bfs();
}
cout<<"ENTER YOUR CHOICE\n1. for show graph\n2.for bfs traversal\n3.for exit\n";
cin>>i;
}
}
void create()
{
int no,nol,i=0,j=0,flag=0;
char s;
start=NULL;
cout<<"Enter the no. of nodes in graph";
cin>>no;
i=0;

while(i<no)
{
cout<<"ENTER THE NAME OF NODE";
cin>>s;
p=new node;
p->data=s;
p->next=NULL;
p->adj=NULL;
p->status=0;
if(start==NULL)
{
start=p;
q=p;
}
else
{
q->next=p;
q=p;
}
i++;
}
p=start;
while(p!=NULL)
{
flag=0;
cout<<"ENTER THE NO. OF ADJACENT TO NODE "<<p->data<<"\n";
cin>>nol;
j=0;
while(j<nol)
{
cout<<"Enter the adjacent node";
cin>>s;
k=new link;
k->nextlink=s;
k->adj=NULL;
k->next=NULL;
if(flag==0)
{
p->adj=k;
l=k;
flag++;
}
else
{
l->adj=k;
l=k;
}
q=start;
while(q!=NULL)
{
if(q->data==s)
{
k->next=q;
break;
}
q=q->next;
}
j++;
}
p=p->next;
}
}
void bfs()
{
char qu[20];
char s;
int i=1,j=0;
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
cout<<"ENTER THE STARTING TRAVERSING NODE";
cin>>s;
for(p=start;p!=NULL;)
{
if(p->data==s)
break;
p=p->next;
}
qu[0]=p->data;
p->status=1;
while(qu[j]!=0)
{
if(qu[j]=='0')
{
break;
}
p=start;
while(p!=NULL)
{
if(p->data==qu[j])
{
break;
}
p=p->next;
}
k=p->adj;
while(k!=NULL)
{
q=k->next;
if(q->status==0)
{
qu[i]=q->data;
q->status=1;
qu[i+1]='0';
i++;
}
k=k->adj;
}
j++;
}
cout<<"\n\nBREADTH FIRST SEARCH RESULT\n\n";
j=0;
while(qu[j]!='0')
{
cout<<qu[j]<<" ";
j++;
}
getch();
}
void show()
{
cout<<"NODE : ADJACENT\n";
p=start;
while(p!=NULL)
{
cout<<" "<<p->data<<" ";
k=p->adj;
while(k!=NULL)
{
cout<<k->nextlink<<", ";
k=k->adj;
}
cout<<"\n";
p=p->next;
}
}


Visit for More Learning http://codesofprogramming.blogspot.in/

No comments:

Post a Comment