Here is a c program to describe the DFS (Depth First Search). Depth First Search is an algorithm which is used to search a Tree or Graph in the programming language. It starts from the Root node and then starts traversing to the next level of Tree and Graph.
Copy the below program and execute it with the help of turbo c or TC bin to see the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include<stdio.h> void DFS(int); int G[10][10],visited[10],n; void 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); } 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); } |
Enter number of vertices:2
Enter adjecency matrix of the graph:12
14
12
5
0
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: c program for depth first search, c programs, c programs with solutions, depth first search c program, depth first search program, depth first search program in c, list of important c programs