C program to implement the Depth First search a graph traversal methods
C program to implement the Depth First search a graph traversal methods
DFS
#include <stdio.h>
int a[20][20], visited[20], n;
void dfs(int v)
{
int i;
visited[v] = 1;
for (i = 1; i <= n; i++)
{
if (a[v][i] && !visited[i])
{
printf("\n %d->%d", v, i);
dfs(i);
}
}
}
int main( )
{
int i, j,v, count = 0;
printf("\n Enter number of vertices:");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
visited[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]);
printf("Enter the starting vertex: ");
scanf("%d", &v);
dfs(v);
return 0;
}
OUTPUT
Enter number of vertices:6
Enter the adjacency matrix:
0 1 1 0 0 0
1 0 1 0 0 0
1 1 0 1 1 0
0 0 1 0 0 0
0 0 1 0 0 1
0 0 0 0 1 0
Enter the starting vertex: 2
2->1
1->3
3->4
3->5
5->6
π» Run This C Program
C program to implement the Depth First search a graph traversal methods
The selected C program is loaded automatically.
Edit the code, provide input through STDIN and
click Run.
The compiler is embedded using OneCompiler.
Your program runs in the embedded C environment;
Study Glance does not execute C code directly on
your web server.