#include<iostream>
using namespace std;
class graphtraversal
{
public:
int size;
int **adj;
void readadj();
void dfs();
void bfs();
};
void graphtraversal::readadj()
{
cout<<"enter no of vertices\n";
cin>>size;
adj=new int *[size];
for(int i=0;i<size;i++)
adj[i]=new int [size];
cout<<"enter adj matrix:\n";
for(int i=0;i<size;i++)
for(int j=0;j<size;j++)
cin>>adj[i][j];
}
void graphtraversal::dfs()
{
int stack[size],top=-1;
int start,visited[size];
for(int i=0;i<size;i++)
visited[i]=0;
cout<<"enter starting node:\n";
cin>>start;
stack[++top]=start;
visited[start]=1;
while(top!=-1)
{
start=stack[top--];
cout<<start<<" ";
for(int i=0;i<size;i++)
{
if(adj[start][i]==1 && visited[i]!=1)
{
stack[++top]=i;
visited[i]=1;
}
}
}
}
void graphtraversal::bfs()
{
int queue[size],f=-1,r=0;
int strt,visited[size];
for(int i=0;i<size;i++)
visited[i]=0;
cout<<"enter starting node\n";
cin>>strt;
queue[r++]=strt;
visited[strt]=1;
while(f!=r-1)
{
strt=queue[++f];
cout<<strt<<" ";
for(int i=0;i<size;i++)
{
if(adj[strt][i]==1 && visited[i]!=1)
{
queue[r++]=i;
visited[i]=1;
}
}
}
}
int main()
{
graphtraversal ob;
int op,n=1;
while(n==1)
{
cout<<"\nenter the option\n";
cout<<"1.read adj\n2.DFS\n3.BFS\n4.exit\n";
cin>>op;
switch(op)
{
case 1:
ob.readadj();
break;
case 2:
ob.dfs();
break;
case 3:
ob.bfs();
break;
case 4:
n=0;
break;
}
}
}
OUTPUT:-
enter the option
1.read adj
2.DFS
3.BFS
4.exit
1
enter no of vertices
4
enter adj matrix:
0
^Z
[4]+ Stopped ./a.out
[b520@localhost ~]$ ./a.out
enter the option
1.read adj
2.DFS
3.BFS
4.exit
1
enter no of vertices
4
enter adj matrix:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
enter the option
1.read adj
2.DFS
3.BFS
4.exit
2
enter starting node:
0
0 2 3 1
enter the option
1.read adj
2.DFS
3.BFS
4.exit
3
enter starting node
0
0 2 3 1
enter the option
1.read adj
2.DFS
3.BFS
4.exit
4
No comments:
Post a Comment