Friday, January 9, 2015

Graph, BFS and DFS traversing in C++

#include<conio.h>
#include<iostream.h>
#include<stdlib.h>

void create();
void dfs();
void bfs();

struct node
{
int data,status;
struct node *next;
struct link *adj;
}*start,*p,*q;

struct link
{
int nextlink;
struct node *next;
struct link *adj;
}*l,*k;

void show();
int main()
{
int choice;
clrscr();
create();
show();
while(1)
{
cout<<"\n-----------------------\n";
cout<<"1: DFS\n2: BSF\n3: Exit\nEnter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
dfs();
break;
case 2:
bfs();
break;
case 3:
exit(0);
break;
default:
cout<<"Incorrect choice!\nRe-enter your choice.";
getch();
}
}
}

void create()
{
int dat,flag=0;
start=NULL;
int no,nol,i=0,j=0;
cout<<"Enter no. of the nodes in the graph: ";
cin>>no;
i=0;
while(i<no)
{
dat=i+1;
p=new node;
p->data=dat;
p->status=0;
p->next=NULL;
p->adj=NULL;
if(start==NULL)
{
start=p;
q=p;

}
else
{
q->next=p;
q=p;
}
i++;
}
p=start;
while(p!=NULL)
{
cout<<"Enter the No. links to "<<p->data<<" ";
cin>>nol;

flag=0;
j=0;
while(j<nol)
{
cin>>dat;

k=new link;
k->nextlink=dat;
k->adj=NULL;
if(flag==0)
{
p->adj=k;
l=k;
flag++;
}
else
{
l->adj=k;
l=k;
}
q=start;
while(q!=NULL)
{
if(q->data==dat)
k->next=q;
q=q->next;
}
j++;
}
p=p->next;
}
cout<<"-------------------------\n";

}


void bfs()
{
int qu[20],i=1,j=0,z;
cout<<"ENTER THE NODE FROM WHICH YOU WANT TO START TRAVERSE";
cin>>z;
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
while(p->data!=z&&p->next!=NULL)
{
p=p->next;
q=p;
}
p=q;
qu[0]=p->data;
p->status=1;
while(1)
{
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++;
}
j=0;
cout<<"Breadth First Search Results\n";
cout<<"---------------------------\n";
while(qu[j]!=0)
{
cout<<qu[j]<<"  ";
j++;
}
cout<<"---------------------------\n";
getch();

}
void show()
{
int i=1;
cout<<"vertax : : adjacent\n";
for(q=start;q!=NULL;q=q->next,i++)
{
cout<<i<<" : ";
k=q->adj;
while(k!=NULL)
{
cout<<k->nextlink<<" ";
k=k->adj;
}
cout<<"\n";
}
}



void dfs()
{
int stack[25],top=1,z;
cout<<"ENTER THE NODE FROM WHICH YOU WNAT TO START TRAVERSE";
cin>>z;
cout<<"Deapth First Search Results\n";
cout<<"---------------------------\n";

p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
q=start;
while(p->data!=z&&p->next!=NULL)
{
p=p->next;
q=p;
}
p=q;
stack[0]=0;
stack[top]=p->data;
p->status=1;
while(1)
{
if(stack[top]==0)
break;
p=start;
while(p!=NULL)
{
if(p->data==stack[top])
break;
p=p->next;
}
cout<<stack[top]<<"  ";
top--;
k=p->adj;
while(k!=NULL)
{
q=k->next;
if(q->status==0)
{
top++;
stack[top]=q->data;
q->status=1;
}
k=k->adj;
}
}
getch();

}

for more Learning visit to http://codesofprogramming.blogspot.in/

No comments:

Post a Comment