Write a C program for Breadth-First-Search (BFS) in a Graph.

for each u ∈ G.V - {s}
              u.color = white
s.color = gray
s.d = 0
Q = ∅
Q.enqueue(s)
while Q ≠ ∅
	      u = Q.dequeue()
         for each v ∈ G.Adj[u]
	           if v.color == white
	                  v.color = gray
	                  v.d = u.d + 1
	                  v.pred = u
	                  Q.enqueue(v)
	         u.color = black

#include <stdio.h>
#include <stdlib.h>

#define MAX_NODES 5

// Structure to represent a node in the graph
typedef struct Node {
    int value;
    int color; // 0: white, 1: gray, 2: black
    int d;     // Distance from source
    struct Node* pred; // Predecessor in BFS traversal
    struct Node* next; // Linked list of adjacent nodes
} Node;

// Queue structure
typedef struct Queue {
    Node* items[MAX_NODES];
    int front;
    int rear;
} Queue;

void enqueue(Queue* q, Node* node) {
    q->items[q->rear++] = node;
}

Node* dequeue(Queue* q) {
    return q->items[q->front++];
}

// Breadth-First Search function
void BFS(Node* graph[], int numNodes, Node* source) {
    Queue q;
    q.front = 0;
    q.rear = 0;

    // Initialize the queue and source node
    enqueue(&q, source);
    source->color = 1; // Gray
    source->d = 0;
    source->pred = NULL;

    while (q.front != q.rear) {
        Node* u = dequeue(&q);
        Node* v = u->next;

        while (v != NULL) {
            if (v->color == 0) { // White
                v->color = 1; // Gray
                v->d = u->d + 1;
                v->pred = u;
                enqueue(&q, v);
            }
            v = v->next;
        }

        u->color = 2; // Black
    }
}

int main() {
    // Create nodes
    Node* nodes[MAX_NODES];
    for (int i = 0; i < MAX_NODES; i++) {
        nodes[i] = (Node*)malloc(sizeof(Node));
        nodes[i]->value = i;
        nodes[i]->color = 0; // White
        nodes[i]->d = -1;    // Distance uninitialized
        nodes[i]->pred = NULL;
        nodes[i]->next = NULL;
    }

    // Add edges (Modify this part to match your graph)
    nodes[0]->next = nodes[1];
    nodes[1]->next = nodes[2];
    nodes[2]->next = nodes[3];
    nodes[3]->next = nodes[4];

    // Perform BFS
    BFS(nodes, MAX_NODES, nodes[0]);

    // Print results
    for (int i = 0; i < MAX_NODES; i++) {
        printf("Node %d: Color: %d, Distance: %d\n", nodes[i]->value, nodes[i]->color, nodes[i]->d);
    }

    // Free allocated memory
    for (int i = 0; i < MAX_NODES; i++) {
        free(nodes[i]);
    }

    return 0;
}

Node 0: Color: 2, Distance: 0
Node 1: Color: 2, Distance: 1
Node 2: Color: 2, Distance: 1
Node 3: Color: 2, Distance: 1
Node 4: Color: 2, Distance: 1

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.