fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to add an edge to the adjacency list
  5. void addEdge(vector<int> adj[], int u, int v) {
  6. adj[u].push_back(v); // Add v to u's list
  7. adj[v].push_back(u); // Add u to v's list (for undirected graph)
  8. }
  9.  
  10. // Function to perform BFS
  11. void BFS(vector<int> adj[], int V, int start) {
  12. vector<bool> visited(V, false); // To keep track of visited nodes
  13. queue<int> q; // Queue for BFS
  14.  
  15. // Start BFS from the given starting node
  16. visited[start] = true;
  17. q.push(start);
  18.  
  19. cout << "BFS traversal starting from node " << start << ": ";
  20. while (!q.empty()) {
  21. int node = q.front();
  22. q.pop();
  23. cout << node << " ";
  24.  
  25. // Visit all unvisited neighbors of the current node
  26. for (int neighbor : adj[node]) {
  27. if (!visited[neighbor]) {
  28. visited[neighbor] = true;
  29. q.push(neighbor);
  30. }
  31. }
  32. }
  33. cout << endl;
  34. }
  35.  
  36. int main() {
  37. int V = 6; // Number of vertices
  38. vector<int> adj[V]; // Adjacency list
  39.  
  40. // Adding edges
  41. addEdge(adj, 0, 1);
  42. addEdge(adj, 0, 2);
  43. addEdge(adj, 1, 3);
  44. addEdge(adj, 1, 4);
  45. addEdge(adj, 2, 4);
  46. addEdge(adj, 3, 5);
  47. addEdge(adj, 4, 5);
  48.  
  49. // Perform BFS starting from node 0
  50. BFS(adj, V, 0);
  51.  
  52. return 0;
  53. }
  54.  
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
BFS traversal starting from node 0: 0 1 2 3 4 5