GRAPH TRAVERSAL




#include<iostream.h>
#include<conio.h>
int a[10][10],n,visited[10],visit1[10];
class graph
{
public:
void searchfrom(int k);
void searchfrom1(int k);
};
void graph::searchfrom(int k)
{
int i;
cout<<"->"<<k;
getch();
visited[k]=1;
for(i=1;i<=n;i++)
{
if(visited[i]==0)
if(a[k][i]!=0)
searchfrom(i);
}
}
void graph::searchfrom1(int k)
{
int i;
cout<<"->"<<k;
getch();
visit1[k]=1;
for(i=1;i<=n;i++)
{
if(visit1[i]==0)
{
if(a[k][i]!=0)
searchfrom1(i);
}
break;
}
}
void main()
{
int i,j,c;
char cont;
clrscr();
graph obj;
a:
cout<<"\nEnter the number of nodes:";
cin>>n;
cout<<"\nEnter the adjacency matrix:";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i!=j)
{
cout<<"\nEnter the value of"<<i<<"-"<<j<<"Element";
cin>>a[i][j];
}
cout<<"\n1.Depth First Search\n2.Breadth First Search\n";
cout<<"\nEnter the choice of traversal:";
cin>>c;
if(c==1)
{
cout<<"\nNode are visited in DFS order\n";
for(i=1;i<=n;i++)
if(visited[i]==0)
obj.searchfrom(i);
}
if(c==2)
{
cout<<"\nNodes are visited in BFS order\n";
for(i=1;i<=n;i++)
if(visit1[i]==0)
obj.searchfrom1(i);
}
cout<<"\nContinue?\n";
cin>>cont;
if(cont=='y'||cont=='Y')
goto a;
getch();
}





OUTPUT:
           
            GRAPH TRAVERSAL

Enter the no of nodes3
Enter the adjacent matrix
Enter the value of 1-2element1
Enter the value of 1-3element2
Enter the value of 2-1element3
Enter the value of 2-3element1
Enter the value of 3-1element5
Enter the value of 3-2element4

 1.depth first search
 2.breadth first searchEnter your choice of traversal1
Node are visited in dfs orders-->1-->2-->3
Do you want to continue?y

Enter the no of nodes3
Enter the adjacent matrix
Enter the value of 1-2element2
Enter the value of 1-3element5
Enter the value of 2-1element5
Enter the value of 2-3element4
Enter the value of 3-1element6
Enter the value of 3-2element5

 1.depth first search
 2.breadth first searchEnter your choice of traversal2
nodes are visited in bfs order-->1-->2-->3
Do you want to continue?n


Comments

Popular posts from this blog

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE

BOOKS DETAILS USING C STRUCTURE

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE