Program to implement graph traversal using DFS

Objective: C program to design graph traversal using Depth First Search

Concept: DFS (Depth First Search) is an algorithm used to search the Tree or Graph. DFS search starts from root node then traversal into left child node and continues, if item found it stops otherwise it continues. The advantage of DFS is it requires less memory compare to Breadth First Search (BFS).

Time Complexities: Let T(n, e) and S(n, e) be the maximum time and maximum -additional space taken by algorithm DFS for an n-vertex and e-edge graph, then S(n, e) = Θ(n) and T(n, e) = Θ(n + e) if adjacency lists are used and T(n, e) =Θ(n²) if adjacency matrices are used.

				
					#include<stdio.h>
#include<conio.h>
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][i] && !reach[i]) {
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[i]=0;
for (j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for (i=1;i<=n;i++) {
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected"); 

else
printf("\n Graph is not connected");
getch();

}

				
			

Leave a Reply