Rotate your phone or change to desktop for better experience

Rotate your phone or change to desktop for better experience

5.Write program to implement the BFS algorithm for a graph. || DAA

#include <stdio.h> 

#include <stdbool.h> 

#define MAX_VERTICES 100 

typedef struct { 

int vertices[MAX_VERTICES]; 

int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES]; 

int numVertices; 

} Graph; 

void initGraph(Graph* g, int numVertices) { 

g->numVertices = numVertices; 

for (int i = 0; i < numVertices; i++) { 

g->vertices[i] = 0; 

for (int j = 0; j < numVertices; j++) { 

g->adjacencyMatrix[i][j] = 0; 

void addEdge(Graph* g, int start, int end) { 

g->adjacencyMatrix[start][end] = 1; 

g->adjacencyMatrix[end][start] = 1; 

void BFS(Graph* g, int startVertex) { 

bool visited[MAX_VERTICES] = {false}; 

int queue[MAX_VERTICES];

int front = 0, rear = 0; 

visited[startVertex] = true; 

queue[rear++] = startVertex; 

while (front < rear) { 

int currentVertex = queue[front++]; 

printf("%d ", currentVertex); 

for (int i = 0; i < g->numVertices; i++) { 

if (g->adjacencyMatrix[currentVertex][i] == 1 && !visited[i]) { 

visited[i] = true; 

queue[rear++] = i; 

int main() { Graph g; 

int numVertices, startVertex; 

printf("Enter the number of vertices: "); 

scanf("%d", &numVertices); 

initGraph(&g, numVertices); 

printf("Enter the adjacency matrix:\n"); 

for (int i = 0; i < numVertices; i++) { 

for (int j = 0; j < numVertices; j++) { 

scanf("%d", &g.adjacencyMatrix[i][j]); 

printf("Enter the starting vertex for BFS: "); 

scanf("%d", &startVertex);

printf("BFS traversal starting from vertex %d: ", startVertex);  

BFS(&g, startVertex); 

return 0; 

}


Post a Comment

0 Comments