C Program: Breadth-First Search (BFS)

This C program demonstrates the Breadth-First Search (BFS) algorithm in a graph. The BFS algorithm is used to traverse or search tree or graph data structures. It starts at a given node (often called the ‘root’ node) and explores all of the neighbor nodes at the present depth prior to moving on to nodes at the next depth level.

Program Explanation

The program includes a Graph structure which represents the graph structure and contains functions to add edges and perform BFS traversal.

Key components of the program include:

  • The Graph structure which uses an array of linked lists to represent the adjacency list of each vertex.
  • The addEdge function to add edges between vertices in the graph.
  • The BFS function to perform the BFS traversal starting from a given vertex.
  • The main function to create the graph, add edges, and initiate the BFS traversal.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_VERTICES 100

// Structure to represent a node in the adjacency list
struct Node {
    int vertex;
    struct Node* next;
};

// Structure to represent a graph
struct Graph {
    int numVertices;
    struct Node* adjLists[MAX_VERTICES];
    bool visited[MAX_VERTICES];
};

// Function to create a node
struct Node* createNode(int v) {
    struct Node* newNode = malloc(sizeof(struct Node));
    newNode->vertex = v;
    newNode->next = NULL;
    return newNode;
}

// Function to create a graph
struct Graph* createGraph(int vertices) {
    struct Graph* graph = malloc(sizeof(struct Graph));
    graph->numVertices = vertices;

    for (int i = 0; i < vertices; i++) { graph->adjLists[i] = NULL;
        graph->visited[i] = false;
    }
    return graph;
}

// Function to add an edge to the graph
void addEdge(struct Graph* graph, int src, int dest) {
    // Add edge from src to dest
    struct Node* newNode = createNode(dest);
    newNode->next = graph->adjLists[src];
    graph->adjLists[src] = newNode;

    // Add edge from dest to src (for undirected graph)
    newNode = createNode(src);
    newNode->next = graph->adjLists[dest];
    graph->adjLists[dest] = newNode;
}

// Function to perform BFS
void BFS(struct Graph* graph, int startVertex) {
    struct Node* queue[MAX_VERTICES];
    int front = 0, rear = 0;

    graph->visited[startVertex] = true;
    queue[rear++] = createNode(startVertex);

    while (front < rear) { struct Node* currentNode = queue[front++]; int currentVertex = currentNode->vertex;
        printf("%d ", currentVertex);

        struct Node* temp = graph->adjLists[currentVertex];
        while (temp) {
            int adjVertex = temp->vertex;
            if (!graph->visited[adjVertex]) {
                graph->visited[adjVertex] = true;
                queue[rear++] = createNode(adjVertex);
            }
            temp = temp->next;
        }
    }
}

int main() {
    struct Graph* graph = createGraph(6);

    addEdge(graph, 0, 1);
    addEdge(graph, 0, 2);
    addEdge(graph, 1, 2);
    addEdge(graph, 1, 3);
    addEdge(graph, 2, 4);
    addEdge(graph, 3, 4);
    addEdge(graph, 3, 5);

    printf("Breadth First Traversal starting from vertex 0:\n");
    BFS(graph, 0);

    return 0;
}

Explanation of the Program:

  1. Graph Structure:
    • struct Node: Represents a node in the adjacency list with a vertex value and a pointer to the next node.
    • struct Graph: Represents the graph with the number of vertices, an array of adjacency lists, and a visited array to keep track of visited vertices.
  2. Functions:
    • createNode(int v): Creates a new node with a given vertex value.
    • createGraph(int vertices): Creates a graph with a specified number of vertices, initializing the adjacency lists and visited array.
    • *addEdge(struct Graph graph, int src, int dest)**: Adds an edge between the source and destination vertices. For an undirected graph, edges are added in both directions.
    • *BFS(struct Graph graph, int startVertex)**: Performs BFS starting from a given vertex. It uses a queue to explore vertices level by level, marking each visited vertex to avoid reprocessing.
  3. Main Function:
    • Creates a graph with 6 vertices.
    • Adds edges between vertices to form the graph structure.
    • Initiates BFS traversal starting from vertex 0 and prints the order of traversal.

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)