#include<stdio.h>
#include<malloc.h>
int num;
struct Queue{
int i;
struct Queue *right,*left;
}*head=NULL,*rear=NULL;
push(int num)
{
struct Queue *tmp=malloc(sizeof(struct Queue));
tmp->i=num;
tmp->right=head;
tmp->left=NULL;
if (head!=NULL)
head->left=tmp;
head=tmp;
if(rear==NULL)
rear=head;
}
int pop()
{
int num=rear->i;
rear=rear->left;
return num;
}
BFS(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
BFS(graph,num,node);
}
#include<malloc.h>
int num;
struct Queue{
int i;
struct Queue *right,*left;
}*head=NULL,*rear=NULL;
push(int num)
{
struct Queue *tmp=malloc(sizeof(struct Queue));
tmp->i=num;
tmp->right=head;
tmp->left=NULL;
if (head!=NULL)
head->left=tmp;
head=tmp;
if(rear==NULL)
rear=head;
}
int pop()
{
int num=rear->i;
rear=rear->left;
return num;
}
BFS(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
BFS(graph,num,node);
}
OUTPUT:-