Friday, June 14, 2013

DEPTH FIRST TRAVERSAL/SEARCH

DEPTH FIRST TRAVERSAL/SEARCH (C++ CODE):

#include<iostream.h>
#include<conio.h>
class graph
{
public :
struct node
 {
 int data;
 node *next;
 }*head[20];
  graph()
 {
top=-1;front=-1;rear=-1;}
int front,rear,n,top,stack[20],queue[20];
void create();
void dfs();
void bfs();
void insert(int t)
 {
rear++;
queue[rear]=t;
 }
int deleteq()
 {
int t;
front++;
t=queue[front];
return t;
 }
int pop()
 {
int t;
  t=stack[top];
  top--;
  return t;
 }
 void push(int t)
 {
  top++;
  stack[top]=t;
 }
};
void graph :: bfs()
{
int num,sv,i,visited[20];
node *t;
cout<<"\n\nEnter starting vertex : ";
cin>>sv;
insert(sv);
for(i=0;i<=n;i++)
{
visited[i]=0;
}
cout<<"\n\nBFS traversal is  :\n";
while(front<rear)
{
num=deleteq();
if(visited[num]==0)
{
cout<<"   "<<num;
visited[num]=1;
}
t=head[num];
while(t!=NULL)
{
if(visited[t->data]==0)
insert(t->data);
t=t->next;
}
cout<<"\n";
      }
}

void graph :: dfs()
{
int num,sv,i,visited[20];
node *t;
cout<<"\n\nEnter the starting vertex :";
cin>>sv;
push(sv);
for(i=1;i<=n;i++)
{
visited[i]=0;
}
cout<<"\n\nThe DFS traversal is :";
while(top!=-1)
{
num=pop();
if(visited[num]==0)
{
cout<<"\t"<<num;
visited[num]=1;
}
t=head[num];
while(t!=NULL)
{
if(visited[t->data]==0)
push(t->data);
t=t->next;
}
      }
   }

void graph :: create()
{
int i,j;
char ans;
node *t,*t1,*p;
cout<<"\nEnter the number of nodes :";
cin>>n;
for(i=1;i<=n;i++)
{
head[i]=NULL;}
do
{
 t=new node;
 t->next=NULL;
 cout<<"\nEnter 2 vertices :";
 cin>>i>>j;
 t->data=j;
 if(head[i]==NULL)
{
 t1=new node;
 t1->next=NULL;
 t1->data=i;
 head[i]=t1;
}
 p=head[i];
 while(p->next!=NULL)
{
 p=p->next;
}
 p->next=t;
 cout<<"\nDo you want to continue (Y/N) :";
 cin>>ans;
}while(ans=='y'||ans=='Y');
}
void main()
{
int ch;
char choice;
clrscr();
graph obj;
obj.create();
do
{
cout<<"\n1.DFS \n2.BFS\n\tEnter your choice :";
cin>>ch;
switch(ch)
{
case 1:
obj.dfs();
break;
case 2:
obj.bfs();
break;
      default:
break;
}
cout<<"\nDo you want to continue (Y/N) :";
cin>>choice;
}while(choice=='y'||choice=='Y');
getch();

}

No comments:

Post a Comment

Thanks for your valuable comment