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:
- 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.
- 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.