Help Me/Question How To Implement Depth First Search Traversal Algorithm Using C?

steve taylor

White Belt
Depth First Search :-
It is the process of visiting the nodes of the given graph .We are using the stack data structure for implement depth search algorithm.
It is also used for finding the shorted path from given source to all other vertices.
Please share Depth First Search algorithm and C program implementation.
 

krishatg

Content Writer
C program for depth first search
int a[20][20],reach[20],n;
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
if(a[v] && !reach)
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main()
{
int i,j,count=0;
clrscr();
printf("\n Enter number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
reach=0;
for(j=1;j<=n;j++)
a[j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[j]);
dfs(1);
printf("\n");
for(i=1;i<=n;i++)
{
if(reach)
count++;
}
if(count==n)
printf("\n Graph is connected");
else
printf("\n Graph is not connected");
getch();
 
Top