#include<stdio.h>
#include<stdlib.h>
#define max 20
void BFS(int adj[20][20],int n,int u);
void addq(int x);
int qempty();
int delq();
int front=-1,rear=-1;
int q[20];
void main()
{
int adj[20][20],visited[10],n,u,v,i,j;
printf("Enter no of vertices:");
scanf("%d",&n);
for(i=1; i<=n; i++)
{ for(j=1; j<=n; j++)
{
adj[i][j]=0;
}
}
printf("Enter edge:");
scanf("%d%d",&u,&v);
while(u!=0)
{
adj[u][v]=1;
adj[v][u]=1;
printf("Enter another edge:");
scanf("%d%d",&u,&v);
}
printf("Enter starting vertex:");
scanf("%d",&u);
BFS(adj,n,u);
}
void BFS(int adj[20][20],int n,int u)
{
int visited[10],v,i;
for(i=1; i<=n; i++)
{
visited[i]=0;
}
addq(u);
while(!qempty())
{
u=delq();
visited[u]=1;
printf("%d ",u);
for(v=1; v<=n; v++)
{
if(adj[u][v]==1&&visited[v]==0)
{
addq(v);
visited[v]=1;
}
}
}
}
int qempty()
{ if(front==rear)
return 1;
else
return 0;
}
int delq()
{
int x;
if(front==rear)
{
printf("Queue is empty\n");
exit(0);
}
else
{
front=front+1;
x=q[front];
return x;
}
}
void addq(int x)
{
if(rear==max-1)
printf("Queue is full\n");
else
{
rear=rear+1;
q[rear]=x;
}
}
Note: Need to be arranged in compiler after copied
OutPut:
Enter no of vertices:6
Enter edge:1 2
Enter another edge:1 3
Enter another edge:2 4
Enter another edge:2 5
Enter another edge:3 5
Enter another edge:4 5
Enter another edge:4 6
Enter another edge:5 6
Enter another edge:0 0
Enter starting vertex:1
1 2 3 4 5