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

BFS

This document contains a C program that implements the Breadth-First Search (BFS) algorithm for traversing a graph. It initializes an adjacency matrix based on user input for vertices and edges, and performs BFS starting from a specified vertex. The program uses a queue to manage the traversal order and prints the order of visited nodes.

Uploaded by

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

BFS

This document contains a C program that implements the Breadth-First Search (BFS) algorithm for traversing a graph. It initializes an adjacency matrix based on user input for vertices and edges, and performs BFS starting from a specified vertex. The program uses a queue to manage the traversal order and prints the order of visited nodes.

Uploaded by

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

#include <stdio.

h>
#include <stdbool.h>

#define MAX 100

int graph[MAX][MAX];
bool visited[MAX];
int queue[MAX];
int front = -1, rear = -1;

// Enqueue function
void enqueue(int value) {
if (rear == MAX - 1) return;
if (front == -1) front = 0;
queue[++rear] = value;
}

// Dequeue function
int dequeue() {
if (front == -1 || front > rear) return -1;
return queue[front++];
}

// BFS function
void BFS(int start, int vertices) {
for (int i = 0; i < vertices; i++)
visited[i] = false;

enqueue(start);
visited[start] = true;

printf("BFS Traversal: ");


while (front <= rear) {
int current = dequeue();
printf("%d ", current);

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


if (graph[current][i] && !visited[i]) {
enqueue(i);
visited[i] = true;
}
}
}
printf("\n");
}

int main() {
int vertices, edges;
int u, v, start;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);

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


scanf("%d", &edges);

// Initialize adjacency matrix


for (int i = 0; i < vertices; i++)
for (int j = 0; j < vertices; j++)
graph[i][j] = 0;

// Read edges
printf("Enter edges (format: u v) [0-based indexing]:\n");
for (int i = 0; i < edges; i++) {
scanf("%d %d", &u, &v);
graph[u][v] = 1;
graph[v][u] = 1; // For undirected graph
}

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


scanf("%d", &start);

BFS(start, vertices);

return 0;
}

You might also like