#include<stdio.h>
#include<malloc.h>
int num;
struct stk{
int i;
struct stk *link;
}*top=NULL;
push(int num)
{
struct stk *tmp=malloc(sizeof(struct stk));
tmp->i=num;
tmp->link=top;
top=tmp;
}
int pop()
{
int num=top->i;
top=top->link;
return num;
}
DFS(int graph[][num],int num,char node[][10])
{
printf("\nEnter the starting element:");
int i,j;
char start[10];
scanf("%s",start);
for(i=0;i<num;i++)
{
if(strcmp(start,node[i])==0)
break;
}
push(i);
int k=0,l=0,flag=0,arr[num],ans;
printf("\nDFS Traversal:-\n ");
while(k<num)
{
flag=0;
ans=pop();
for(l=k-1;l>=0;l--)
if(ans==arr[l]) flag=1;
if(flag==0)
{
printf("%s ",node[ans]);
arr[k++]=ans;
for(j=0;j<num;j++)
{
if(graph[ans][j]!=0)
{
push(j);
}
}
}
}
}
main()
{
printf("\nEnter the number of elements:");
int i,j;
scanf("%d",&num);
int graph[num][num];
char node[num][10];
printf("\nEnter the elements\n:");
for(i=0;i<num;i++)
scanf("%s",&node[i]);
printf("\nEnter the graph:\n");
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
{
scanf("%d",&graph[i][j]);
}
}
//
//DFS Traversal
DFS(graph,num,node);
}
#include<malloc.h>
int num;
struct stk{
int i;
struct stk *link;
}*top=NULL;
push(int num)
{
struct stk *tmp=malloc(sizeof(struct stk));
tmp->i=num;
tmp->link=top;
top=tmp;
}
int pop()
{
int num=top->i;
top=top->link;
return num;
}
DFS(int graph[][num],int num,char node[][10])
{
printf("\nEnter the starting element:");
int i,j;
char start[10];
scanf("%s",start);
for(i=0;i<num;i++)
{
if(strcmp(start,node[i])==0)
break;
}
push(i);
int k=0,l=0,flag=0,arr[num],ans;
printf("\nDFS Traversal:-\n ");
while(k<num)
{
flag=0;
ans=pop();
for(l=k-1;l>=0;l--)
if(ans==arr[l]) flag=1;
if(flag==0)
{
printf("%s ",node[ans]);
arr[k++]=ans;
for(j=0;j<num;j++)
{
if(graph[ans][j]!=0)
{
push(j);
}
}
}
}
}
main()
{
printf("\nEnter the number of elements:");
int i,j;
scanf("%d",&num);
int graph[num][num];
char node[num][10];
printf("\nEnter the elements\n:");
for(i=0;i<num;i++)
scanf("%s",&node[i]);
printf("\nEnter the graph:\n");
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
{
scanf("%d",&graph[i][j]);
}
}
//
//DFS Traversal
DFS(graph,num,node);
}
OUTPUT:-