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 = 12; // 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, 0, 4);
  44. addEdge(adj, 1, 4);
  45.  
  46. addEdge(adj, 2, 4);
  47. addEdge(adj, 2, 9);
  48. addEdge(adj, 2, 5);
  49. addEdge(adj, 2, 10);
  50. addEdge(adj, 9, 11);
  51. addEdge(adj, 10, 11);
  52. addEdge(adj, 5, 6);
  53. addEdge(adj, 5, 7);
  54. addEdge(adj, 5, 8);
  55. addEdge(adj, 7, 8);
  56.  
  57. // Perform BFS starting from node 0
  58. BFS(adj, V, 0);
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
BFS traversal starting from node 0: 0 1 2 4 9 5 10 11 6 7 8