Program to traverse a graph using breadth-first search traversal

//program to traverse a graph using breadth first search traversal


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

class queue
{
	int q[20],front,rear;

	public:
		queue()
		{
			front=rear=0;
		}
		void insert(int);
		int delet();
		int isempty();
};

void queue::insert(int item)
{
	if(front==0)
		front++;
	q[++rear]=item;
}

int queue::delet()
{
	int item;

	item=q[front++];
	if(front>rear)
		front=rear=0;

	return item;
}

int queue::isempty()
{
	if(front==0)
		return 1;
	return 0;
}

class graph
{
	private:
		int n,a[20][20],reach[20];
		queue qu;

	public:
		graph();
		void setdata();
		void bfs();
};

void graph::graph()
{
	int i;
	for(i=0;i<=20;i++)
		reach[i]=0;
}

void graph::setdata()
{
	int i,j;

	cout<<"\nEnter number of vertices: ";
	cin>>n;

	cout<<"\nEnter adjacency matrix: ";
	for(i=1;i<=n;i++)
	{
		cout<<"\nEnter "<<i<<" row: ";
		for(j=1;j<=n;j++)
			cin>>a[i][j];
	}
}

void graph::bfs()
{
	int v=1,i;

	qu.insert(v);
	reach[v]=1;

	while(!(qu.isempty()))
	{
		v=qu.delet();

		cout<<v<<"\t";

		for(i=1;i<=n;i++)
			if(a[v][i]==1 && reach[i]==0)
			{
				qu.insert(i);
				reach[i]=1;
			}
	}
}

void main()
{
	graph g;
	clrscr();

	g.setdata();

	cout<<"\n\nDFS traversal of given graph is: \n\t";
	g.bfs();

	getch();
}
Chitra
Chitra

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in