Wednesday, March 26, 2014

C++ code to Represent graph using adjacency list and perform DFS and BFS

Code :
#define infinity 9999
#define MAX 20
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
class Q
{
int data[30];
int R,F;
public:
Q()
{
R=F=-1;
}
void init()
{
R=F=-1;
}
int empty()
{
if(R==-1)
return 1;
return 0;
}
void insert(int x)
{
if(empty())
R=F=0;
else
R=R+1;
data[R]=x;
}
int Delete()
{
int x=data[F];
if(R==F)
R=F=-1;
else
F=F+1;
return(x);
}
};
struct node
{
node *next;
int vertex;
};
class graph
{
int visited[MAX];
node *G[20];
int n;
void insert(int vi,int vj);
void DFS1(int);
public:
graph()
{
n=0;
}
void readgraph();
void BFS(int);
void DFS(int);
};
void graph::DFS(int start)
{
for(int i=0;i<n;i++)
visited[i]=0;
DFS1(start);
}
void graph::BFS(int v)
{
int i,w;
Q q;
node *p;
for(i=0;i<n;i++)
visited[i]=0;
q.insert(v);
cout<<” “<<v;
visited[v]=1;
while(!q.empty())
{
v=q.Delete();
for(p=G[v];p!=NULL;p=p->next)
{
w=p->vertex;
if(visited[w]==0)
{
q.insert(w);
visited[w]=1;
cout<<” “<<w;
}
}
}
}
void graph::DFS1(int i)
{
node *p;
cout<<” “<<i;
p=G[i];
visited[i]=1;
while(p!=NULL)
{
i=p->vertex;
if(!visited[i])
DFS1(i);
p=p->next;
}
}
void graph::readgraph()
{
int i,vi,vj,no_of_edges;
cout<<”\n\nEnter number of vertices: “;
cin>>n;
for(i=0;i<n;i++)
G[i]=NULL;
cout<<”\n\nEnter number of edges: “;
cin>>no_of_edges;
for(i=0;i<no_of_edges;i++)
{
cout<<”\n\nEnter an edge(u,v): “;
cin>>vi>>vj;
insert(vi,vj);
insert(vj,vi);
}
}
void graph::insert(int vi,int vj)
{
node *p,*q;
q=new node ;
q->vertex=vj;
q->next=NULL;
if(G[vi]==NULL)
G[vi]=q;
else
{
p=G[vi];
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
void main()
{
int choice,start,n;
graph g1;
clrscr();
cout<<”\n\n\t\t\t\t\t\t\t\t\t\t\t\t…. BFS & DFS Of Graph …. “;
cout<<”\n\nÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ”;
do
{
cout<<”\nÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ”;
cout<<”\n\n MENU: “;
cout<<”\n\n\t1.Create a graph\n\n\t2.BFS\n\n\t3.DFS\n\n\t4.Exit”;
cout<<”\nÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ”;
cout<<”\n\nEnter Your Choice: “;
cin >>choice;
switch(choice)
{
case 1:
g1.readgraph();
break;
case 2:
cout<<”\n\nEnter starting Vertex: “;
cin>>start;
cout<<”\n\nBFS of graph is:\n\n”;
g1.BFS(start);
break;
case 3:
cout<<”\n\nEnter starting Vertex: “;
cin>>start;
cout<<”\n\nDFS of graph is:\n\n”;
g1.DFS(start);
break;
}
}while(choice!= 4);
}

No comments:

Post a Comment