consider the following graph and its adjacency matrix:
One of the DFS traversal of the graph is
0 1 2 3 4
Program :DFS
#include<stdio.h>
int a[20][20],q[20],visited[20],n;
void dfs(int v)
{
int i;
for (i=0;i<n;i++) // check all the vertices in the graph
{
if(a[v][i] != 0 && visited[i] == 0) // adjacent to v and not visited
{
visited[i]=1; // mark the vertex visited
printf("%d ",i);
dfs(i);
}
}
}
int main()
{
int v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=0;i<n;i++)
{
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=0;i<n;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
printf("\n DFS traversal is:\n");
visited[v]=1; // mark the starting vertex as visited
printf("%d ",v);
dfs(v);
}
Output:
Output:
Enter the number of vertices: 5
Enter graph data in matrix form:
0 1 0 0 1
1 0 1 1 1
0 1 0 1 0
0 1 1 0 1
1 1 0 1 0
Enter the starting vertex:0
DFS traversal is:
0 1 2 3 4
One of the DFS traversal of the graph is
0 1 2 3 4
Program :DFS
#include<stdio.h>
int a[20][20],q[20],visited[20],n;
void dfs(int v)
{
int i;
for (i=0;i<n;i++) // check all the vertices in the graph
{
if(a[v][i] != 0 && visited[i] == 0) // adjacent to v and not visited
{
visited[i]=1; // mark the vertex visited
printf("%d ",i);
dfs(i);
}
}
}
int main()
{
int v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=0;i<n;i++)
{
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=0;i<n;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
printf("\n DFS traversal is:\n");
visited[v]=1; // mark the starting vertex as visited
printf("%d ",v);
dfs(v);
}
Output:
Output:
Enter the number of vertices: 5
Enter graph data in matrix form:
0 1 0 0 1
1 0 1 1 1
0 1 0 1 0
0 1 1 0 1
1 1 0 1 0
Enter the starting vertex:0
DFS traversal is:
0 1 2 3 4
I have a coding website, I like your codes. I want to publish your programming codes on my website with your names. I will give you refer link from my website. can you permit me ? ping me on lokeshnow@gmail.com
ReplyDeleteI have a coding website, I like your codes. I want to publish your programming codes on my website with your names. I will give you refer link from my website. can you permit me ? ping me on lokeshnow@gmail.com
ReplyDeleteyou have my permission, you publish my code on your website with my name and link to my blog
Delete