#include <bits/stdc++.h>
using namespace std;
// Function to add an edge to the adjacency list
void addEdge(vector<int> adj[], int u, int v) {
adj[u].push_back(v); // Add v to u's list
adj[v].push_back(u); // Add u to v's list (for undirected graph)
}
// Function to perform BFS
void BFS(vector<int> adj[], int V, int start) {
vector<bool> visited(V, false); // To keep track of visited nodes
queue<int> q; // Queue for BFS
// Start BFS from the given starting node
visited[start] = true;
q.push(start);
cout << "BFS traversal starting from node " << start << ": ";
while (!q.empty()) {
int node = q.front();
q.pop();
cout << node << " ";
// Visit all unvisited neighbors of the current node
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
cout << endl;
}
int main() {
int V = 6; // Number of vertices
vector<int> adj[V]; // Adjacency list
// Adding edges
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 4);
addEdge(adj, 3, 5);
addEdge(adj, 4, 5);
// Perform BFS starting from node 0
BFS(adj, V, 0);
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgovLyBGdW5jdGlvbiB0byBhZGQgYW4gZWRnZSB0byB0aGUgYWRqYWNlbmN5IGxpc3QKdm9pZCBhZGRFZGdlKHZlY3RvcjxpbnQ+IGFkaltdLCBpbnQgdSwgaW50IHYpIHsKICAgIGFkalt1XS5wdXNoX2JhY2sodik7IC8vIEFkZCB2IHRvIHUncyBsaXN0CiAgICBhZGpbdl0ucHVzaF9iYWNrKHUpOyAvLyBBZGQgdSB0byB2J3MgbGlzdCAoZm9yIHVuZGlyZWN0ZWQgZ3JhcGgpCn0KCi8vIEZ1bmN0aW9uIHRvIHBlcmZvcm0gQkZTCnZvaWQgQkZTKHZlY3RvcjxpbnQ+IGFkaltdLCBpbnQgViwgaW50IHN0YXJ0KSB7CiAgICB2ZWN0b3I8Ym9vbD4gdmlzaXRlZChWLCBmYWxzZSk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