Write a program to implement DFS traversal Of a graph in C program.
CODING:
#include<stdio.h>
#include<conio.h>
#define max 10
void dfs(int graph[][max],int visited[],int start)
{
int stack[max],top=-1,i;
printf("%c-",start+65);
stack[++top]=start;
visited[start]=1;
while(top!=-1)
{
start=top;
for(i=0;i<max;i++)
{
if(graph[start][i] && visited[i]==0)
{
stack[++top]=i;
printf("%c-",i+65);
visited[i]=1;
break;
}
}
if(i==max)
top--;
}
}
void main()
{
int visited[max]={0};
int graph[max][max],i,j;
clrscr();
printf("\nENTER THE ADJACENCY MATRIX FROM:");
for(i=0;i<max;i++)
for(j=0;j<max;j++)
scanf("%d",&graph[i][j]);
printf("DFS TRAVERSAL...");
dfs(graph,visited,0);
getch();
}
CODING:
#include<stdio.h>
#include<conio.h>
#define max 10
void dfs(int graph[][max],int visited[],int start)
{
int stack[max],top=-1,i;
printf("%c-",start+65);
stack[++top]=start;
visited[start]=1;
while(top!=-1)
{
start=top;
for(i=0;i<max;i++)
{
if(graph[start][i] && visited[i]==0)
{
stack[++top]=i;
printf("%c-",i+65);
visited[i]=1;
break;
}
}
if(i==max)
top--;
}
}
void main()
{
int visited[max]={0};
int graph[max][max],i,j;
clrscr();
printf("\nENTER THE ADJACENCY MATRIX FROM:");
for(i=0;i<max;i++)
for(j=0;j<max;j++)
scanf("%d",&graph[i][j]);
printf("DFS TRAVERSAL...");
dfs(graph,visited,0);
getch();
}
Comments
Post a Comment