Breadth-First Search (BFS) is an algorithm for traversing or searching tree or graph data structures. It explores all the neighbor nodes at the present depth prior to moving on to nodes at the next depth level. BFS is particularly useful for finding the shortest path on unweighted graphs.
Initialize:
Process the Queue:
Repeat until all nodes are visited.
Here’s an implementation of BFS using an adjacency list representation of a graph in C++:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Graph {
private:
int V; // Number of vertices
vector<vector<int>> adj; // Adjacency list
public:
Graph(int v) : V(v), adj(v) {}
void addEdge(int u, int v) {
adj[u].push_back(v); // Add edge from u to v
adj[v].push_back(u); // If undirected graph, also add edge from v to u
}
void BFS(int start) {
vector<bool> visited(V, false); // Track visited vertices
queue<int> q; // Queue for BFS
visited[start] = true; // Mark the start node as visited
q.push(start); // Enqueue the start node
while (!q.empty()) {
int node = q.front(); // Get the front node
cout << node << " "; // Process the node
q.pop(); // Dequeue the front node
// Visit all the adjacent nodes
for (int i : adj[node]) {
if (!visited[i]) { // If not visited
visited[i] = true; // Mark as visited
q.push(i); // Enqueue the adjacent node
}
}
}
cout << endl; // New line after traversal
}
};
int main() {
Graph g(5); // Create a graph with 5 vertices
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
cout << "BFS Traversal starting from vertex 0: ";
g.BFS(0); // Start BFS from vertex 0
return 0;
}
Graph Class:
BFS Function:
Main Function:
Time Complexity:
Space Complexity:
Breadth-First Search is a powerful traversal algorithm that systematically explores all vertices at the current depth level before moving deeper. Its use of a queue allows for efficient exploration of nodes, making it suitable for various applications, particularly in networking and pathfinding. Understanding BFS is essential for solving problems related to graph traversal and analysis.
Open this section to load past papers