[go: up one dir, main page]

0% found this document useful (0 votes)
17 views1 page

6.BFS Adjacency Matrix

This C program implements a Breadth-First Search (BFS) algorithm for traversing an undirected graph using an adjacency matrix. It initializes the graph based on user input for the number of vertices and edges, then performs BFS starting from a specified node. The program utilizes a queue to manage the nodes to be visited and an array to track visited nodes.

Uploaded by

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

6.BFS Adjacency Matrix

This C program implements a Breadth-First Search (BFS) algorithm for traversing an undirected graph using an adjacency matrix. It initializes the graph based on user input for the number of vertices and edges, then performs BFS starting from a specified node. The program utilizes a queue to manage the nodes to be visited and an array to track visited nodes.

Uploaded by

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

#include<stdio.

h>
#define max 100
int adj[max][max];//adjacency matrix
int visited[max];//visited array
int queue[max];//queue for BFS
int front=0,rear=-1;
void enqueue(int v)
{
queue[++rear]=v;
}
int dequeue()
{
return queue[front++];
}
void BFS(int start,int n)
{
enqueue(start);
visited[start]=1;
while(front<=rear)
{
int v=dequeue();
printf("%d ",v);
for(int i=0;i<n;i++)
{
if(adj[v][i]==1 && visited[i]==0)
{
enqueue(i);
visited[i]=1;
}
}
}
}
int main()
{
int n,e;
scanf("%d",&n);//no.of vertices
scanf("%d",&e);//no.of edges
for(int i=0;i<n;i++)
{
visited[i]=0;
for(int j=0;j<n;j++)
{
adj[i][j]=0;
}
}
//initialising adjacency matrix and visited array
for(int i=0;i<e;i++)
{
int u,v;
scanf("%d %d",&u,&v);
adj[u][v]=1;
adj[v][u]=1;//because undirected graph
}
int start;
scanf("%d",&start);//starting node
BFS(start,n);
return 0;
}

You might also like