Exp 10 DFS
Exp 10 DFS
Operation
Visit 0
Visit 1
Visit 3
Visit 4
Finish 4
Adjacent Vertex
1,2,3,4
0,3,4
0,1,4
0,1,3
Finish 3
Finish 1
Visit 2
Visit 5
Visit 6
Finish 6
Finish 5
Finish 2
Finish 0
43
431
0,5,6
2,6
2,5
01342
013425
0134256
4316
43165
431652
4316520
Program
#include<stdio.h>
void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]
int main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
//visited is initialized to zero
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
return 0;
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}