Program to traverse a graph using depth first search traversal

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

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

class graph
{
	private:
		int n,a[20][20],reach[20],stack[20],top;

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

void graph::graph()
{
	int i;
	for(i=0;i<=20;i++)
		reach[i]=0;
	top=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::dfs()
{
	int v=1,i;

	stack[++top]=v;
	reach[v]=1;

	while(top!=0)
	{
		v=stack[top--];
		cout<<v<<"\t";
		for(i=1;i<=n;i++)
			if(a[v][i]==1 && reach[i]==0)
			{
				stack[++top]=i;
				reach[i]=1;
			}
	}
}

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

	g.setdata();

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

	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