Write a program to implement BFS traversal Of a graph in C program.
CODING:
#include<stdio.h>
#include<conio.h>
#define max 10
void bfs(int graph[][max],int visited[],int start)
{
int queue[max],front=-1,rear=-1,i;
queue[++rear]=start;
visited[start]=1;
while(rear!=front)
{
start=queue[++front];
if(start==4)
printf("5\t");
else
printf("%c\t",start+65);
for(i=0;i<max;i++)
{
if(graph[start][i]==1 && visited[i]==0)
{
queue[++rear]=i;
visited[i]=1;
}
}
}
}
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("BFS TRAVERSAL...");
bfs(graph,visited,0);
getch();
}
CODING:
#include<stdio.h>
#include<conio.h>
#define max 10
void bfs(int graph[][max],int visited[],int start)
{
int queue[max],front=-1,rear=-1,i;
queue[++rear]=start;
visited[start]=1;
while(rear!=front)
{
start=queue[++front];
if(start==4)
printf("5\t");
else
printf("%c\t",start+65);
for(i=0;i<max;i++)
{
if(graph[start][i]==1 && visited[i]==0)
{
queue[++rear]=i;
visited[i]=1;
}
}
}
}
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("BFS TRAVERSAL...");
bfs(graph,visited,0);
getch();
}
Comments
Post a Comment