DFS
#include<iostream>
#define M 20
using namespace std;
int adj[M][M],c[M],p[M],d[M],f[M],time;
void dfs_visit(int adj[][M],int i,int v)
{
int j;
c[i]=1;
++time;
d[i]=time;
cout<<i<<" ";
for ( j = 0; j < v; j++)
{
if(adj[i][j]==1&&c[j]==0)
{
p[j]=i;
dfs_visit(adj,j,v);
}
}
c[i]=2;
++time;
f[i]=time;
}
void dfs(int adj[][M],int v)
{
int i,j;
time=0;
for ( i = 0; i < v; i++)
{
c[i]=0;
p[j]=-1;
}
for(i=0;i<v;i++)
{
if(c[i]==0)
{
dfs_visit(adj,i,v);
}
}
}
int main()
{
int s,v,i,j;
cout<<"enter the number of vertex";
cin>>v;
cout<<endl<<"Enter the adjacent matrix";
for(i=0;i<v;++i)
{
for(j=0;j<v;++j)
{
cin>>adj[i][j];
}
}
dfs(adj,v);
}
Comments
Post a Comment