fork download
  1. #include <bits/stdc++.h>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. int main() {
  6. int n;
  7. cin >> n;
  8.  
  9. unordered_map<int, vector<int>> G;
  10.  
  11. // Input edges
  12. for (int i = 0; i < n; i++) {
  13. int a, b;
  14. cin >> a >> b;
  15.  
  16. G[a].push_back(b);
  17. }
  18.  
  19. // Queue and visited array
  20. queue<int> q;
  21. vector<bool> visited(n + 1, false);
  22.  
  23. // Insert root (1)
  24. q.push(1);
  25. visited[1] = true;
  26.  
  27. // BFS traversal
  28. while (!q.empty()) {
  29. int front = q.front();
  30. q.pop();
  31.  
  32. cout << front << " ";
  33.  
  34. for (int child : G[front]) {
  35. if (!visited[child]) {
  36. visited[child] = true;
  37. q.push(child);
  38. }
  39. }
  40. }
  41.  
  42. return 0;
  43. }
Success #stdin #stdout 0s 544KB
stdin
5
1 2
1 3
2 4
2 5
3 6
stdout
1 2 3 4 5 6