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 class which represents the graph structure and contains methods to add edges and perform BFS traversal.

Key components of the program include:

  • The Graph class which uses an array of vectors to represent the adjacency list of each vertex.
  • The addEdge method to add edges between vertices in the graph.
  • The BFS method to perform the BFS traversal starting from a given vertex.
  • The main method to create the graph, add edges, and initiate the BFS traversal.
#include <iostream>
#include <list>
#include <vector>
#include <queue>
using namespace std;

/**
 * Class to represent a graph using an adjacency list.
 */
class Graph {
    int numVertices;
    vector<list> adjLists;

public:
    // Constructor
    Graph(int vertices);

    // Function to add an edge to the graph
    void addEdge(int src, int dest);

    // Function to perform BFS
    void BFS(int startVertex);
};

// Constructor to initialize the graph
Graph::Graph(int vertices) {
    numVertices = vertices;
    adjLists.resize(vertices);
}

/**
 * Function to add an edge to the graph.
 * @param src - The source vertex.
 * @param dest - The destination vertex.
 */
void Graph::addEdge(int src, int dest) {
    adjLists[src].push_back(dest);
    adjLists[dest].push_back(src); // For undirected graph, add this line
}

/**
 * Function to perform BFS traversal from a given vertex.
 * @param startVertex - The starting vertex for BFS traversal.
 */
void Graph::BFS(int startVertex) {
    vector visited(numVertices, false);
    queue q;

    visited[startVertex] = true;
    q.push(startVertex);

    while (!q.empty()) {
        int currentVertex = q.front();
        cout << currentVertex << " ";
        q.pop();

        for (auto i = adjLists[currentVertex].begin(); i != adjLists[currentVertex].end(); ++i) {
            int adjVertex = *i;
            if (!visited[adjVertex]) {
                visited[adjVertex] = true;
                q.push(adjVertex);
            }
        }
    }
}

int main() {
    Graph g(6);

    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 4);
    g.addEdge(3, 4);
    g.addEdge(3, 5);

    cout << "Breadth First Traversal starting from vertex 0:\n";
    g.BFS(0);

    return 0;
}

Explanation of the Program:

  1. Graph Class:
    • Graph(int vertices): Constructor to initialize the graph with a specified number of vertices. Each vertex is represented as an index in an array of vectors.
    • void addEdge(int src, int dest): Method to add an edge between two vertices. For undirected graphs, the edge is added in both directions.
    • void BFS(int startVertex): Method to perform BFS starting from a given vertex. It uses a queue to explore vertices level by level, marking each visited vertex to avoid reprocessing.
  2. 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 :)