0% found this document useful (0 votes)
8 views2 pages

Breadth First Search

The document contains a C program that implements the Breadth First Search (BFS) algorithm for graph traversal. It prompts the user to input the number of vertices and the adjacency matrix representing the graph, then performs BFS starting from a specified vertex. The output displays the order of vertices visited during the traversal.

Uploaded by

golladeepu19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Breadth First Search

The document contains a C program that implements the Breadth First Search (BFS) algorithm for graph traversal. It prompts the user to input the number of vertices and the adjacency matrix representing the graph, then performs BFS starting from a specified vertex. The output displays the order of vertices visited during the traversal.

Uploaded by

golladeepu19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Breadth First Search:

#include<stdio.h>

void bfs(int v);

int a[20][20],queue[20],visited[20],n,front=-1,rear=-1;

void main()

int v,i,j;
printf("\nEnter the number of vertices:");

scanf("%d",&n);

printf("\nEnter graph data in matrix form:\n");

for (i=1;i<=n;i++)
{

for (j=1;j<=n;j++)

scanf("%d",&a[i][j]);

for(i=1;i<=n;i++)

{
visited[i]=0;

printf("\nEnter the starting vertex:");

scanf("%d",&v);

front=rear=0;
queue[rear]=v;

visited[v]=1;

printf("\nBFS traversal is:\n");

printf("%d",v);

bfs(v);

}
void bfs(int v)
{

int i;

for (i=1;i<=n;i++)

if(a[v][i] !=0 && visited[i] == 0)

{
rear=rear+1;

queue[rear]=i;

visited[i]=1;

printf("%d",i);
}

front=front+1;

if(front<=rear)

bfs(queue[front]);

Output:

Enter the number of vertices:4

Enter graph data in matrix form:

0110

1001

1001
0110

Enter the starting vertex:1

BFS traversal is:

1234

You might also like