Java Program: Breadth-First Search (BFS)

This Java program demonstrates the Breadth-First Search (BFS) algorithm in a graph. The program includes a Graph class with methods to add edges and perform BFS traversal. Detailed documentation is provided within the code.

import java.util.*;

/**
 * Represents a graph using an array of adjacency lists.
 */
class Graph {
    private int numVertices;
    private LinkedList<Integer> adjLists[];

    /**
     * Constructor to initialize the graph with a specified number of vertices.
     * 
     * @param vertices The number of vertices in the graph.
     */
    Graph(int vertices) {
        numVertices = vertices;
        adjLists = new LinkedList[vertices];
        for (int i = 0; i < vertices; i++) {
            adjLists[i] = new LinkedList<>();
        }
    }

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

    /**
     * Performs a Breadth-First Search (BFS) starting from a given vertex.
     * 
     * @param startVertex The starting vertex for the BFS traversal.
     */
    void BFS(int startVertex) {
        boolean visited[] = new boolean[numVertices];
        LinkedList<Integer> queue = new LinkedList<>();

        visited[startVertex] = true;
        queue.add(startVertex);

        while (queue.size() != 0) {
            startVertex = queue.poll();
            System.out.print(startVertex + " ");

            Iterator<Integer> i = adjLists[startVertex].listIterator();
            while (i.hasNext()) {
                int n = i.next();
                if (!visited[n]) {
                    visited[n] = true;
                    queue.add(n);
                }
            }
        }
    }

    /**
     * The main method to create a graph and initiate a BFS traversal.
     * 
     * @param args Command-line arguments (not used).
     */
    public static void main(String args[]) {
        Graph g = new Graph(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);

        System.out.println("Breadth First Traversal starting from vertex 0:");
        g.BFS(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 LinkedLists.
    • 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 Method:
    • 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 :)