fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. // your code goes here
  6. int n, m;
  7. cin >> n >> m;
  8. vector<vector<int>> matrix(n+5);
  9.  
  10. for (int i = 1; i <= m; i++){
  11. int a, b;
  12. cin >> a >> b;
  13. matrix[a].push_back(b);
  14. matrix[b].push_back(a);
  15. }
  16.  
  17. int source = 1; // here we are taking source as 1 because our input will be as source 1.
  18. // this source will only work with our input.
  19. // for another input we have to change our source.
  20.  
  21. // vector<int> used(n+5,0);
  22. unordered_map<int, int> used;
  23. queue<int> q;
  24. q.push(source);
  25.  
  26. used[source] = 1;
  27.  
  28. while(!q.empty()){
  29. int removed = q.front();
  30. cout << removed << endl;
  31. q.pop();
  32.  
  33. for (int i : matrix[removed]){
  34. if(used[i] == 0){
  35. q.push(i);
  36. used[i] = 1;
  37. }
  38. }
  39. }
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 5292KB
stdin
8 8
1 2
1 4
1 3
1 5
3 6
4 6
2 10
6 9
stdout
1
2
4
3
5
10
6
9