Sunteți pe pagina 1din 4

#include<iostream.

h>
#include<conio.h>
#define max 15
#include<process.h>
class node1;
class node2
{ public:
node1 *adr;
node2 *next;
node2()
{adr=0;
next=0;
}
};
class node1
{
public:
char clr;
char key;
int d;
node1 *parent;
node2 *next;
node1 *nn;
node1(char k)
{ clr='w';
key=k;
next=0;
d=9999;
parent=0;
nn=0;
}
};
class graph
{public:
int n;
char k;
node1 *v[max]; //=new node1[max];
node1 *first;
node1 *last;
graph(int t)
{n=t;
first=0;
last=0;
}

void getvertex()
{ cout<<"enter the vertices\n";
for(int i=0;i<n;i++)
{cout<< "enter the vertex\n";
cin>>k;
v[i]=new node1(k);
}
}
void getadj()
{
for(int i=0;i<n;i++)
{ cout<<"Vertex is "<<v[i]->key<<":\n";
cout<<"enter 1 to insert adjacent list of vertex \n";
int ch;
cin>>ch;
while(ch==1)
{ cout<<"enter the element\n";
cin>>k;
node2 *p=new node2();
int j;
for(j=0;j<n;j++)
{ if(v[j]->key==k)
{ p->adr=v[j];
break;
}
}
node2 *q;
if(v[i]->next==0)
v[i]->next=p;
else
{
q=v[i]->next;
while(q->next!=0)
q=q->next;
q->next=p;
}
cout<<"Enter 1 to add more nodes to adjacent list of this vertex";
cin>>ch;
} // end while
} // end for
} // end getadj
void printadj()
{ for(int i=0;i<n;i++)
{ cout<<"adjacent list of "<<v[i]->key<<":\n";
if(v[i]->next)
{ node2 *q=v[i]->next;
while(q)
{cout<<q->adr->key<<" ";
q=q->next;
}
}
cout<<"\n";
}
} // end printadj()

void enqueue(node1 *t)


{ if(first==0)
first=last=t;
else
{node1 *p=first;
while(p->nn)
p=p->nn;
p->nn=t;
last=t;
}
} //end enqueue()
node1* dequeue()
{ if(first==0)
{cout<<"the queue is empty\n";
return 0;
}
else
{node1 *p=first;
first=first->nn;
if(!first)
last=0;
p->nn=0;
return p;
}
} // end dequeue

void bfs()
{ cout<<"enter the source vertex\n";
cin>>k;
int j;
node1 *s;
for(j=0;j<n;j++)
{ if(v[j]->key==k)
{ s=v[j];
break;
}
}
if(j==n)
{cout<<"Error!!";
exit(1);
}
s->clr='g';
s->d=0;
enqueue(s);
node1 *u;
node2 *v;
while(first!=0)
{u=dequeue();
if(u->next)
{v=u->next;
while(v)
{if(v->adr->clr=='w')
{v->adr->clr='g';
v->adr->parent=u;
v->adr->d=v->adr->parent->d+1;
enqueue(v->adr);
}
v=v->next;
}
u->clr='b';
}
}
} // end of bfs()
void print()
{cout<<"Vertex Parent Level\n";
for(int i=0;i<n;i++)
{cout<<v[i]->key<<"\t"<<v[i]->parent->key<<"\t"<<v[i]->d;
cout<<"\n";
}
}

}; // end of class "graph"


void main()
{ clrscr();
int n;
cout<<"Enter no. of vertices:";
cin>>n;
graph obj(n);
obj.getvertex();
obj.getadj();
obj.printadj();
obj.bfs();
obj.print();
getch();
}

S-ar putea să vă placă și