fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void dfs(int node, vector<int> Graph[], vector<int>& vis, vector<int>& parent) {
  5. cout << node << endl;
  6.  
  7. vis[node] = 1;
  8.  
  9. for(auto u : Graph[node]) { // iterating all children "u" of "node"
  10. if(vis[u] == 0) {
  11. // if this node/branch has never been visited before
  12. // just go into it and search it using dfs in recursion
  13. parent[u] = node;
  14. dfs(u, Graph, vis, parent);
  15. }
  16. }
  17. }
  18.  
  19. int main() {
  20. int n;
  21. cin >> n;
  22.  
  23. int m;
  24. cin >> m;
  25.  
  26. vector<int> Graph[n+5];
  27.  
  28. for(int i=0; i<m; i++) {
  29. int x, y;
  30.  
  31. cin >> x >> y;
  32.  
  33. Graph[x].push_back(y);
  34. Graph[y].push_back(x);
  35. }
  36.  
  37. vector<int> vis(n+5, 0);
  38. vector<int> parent(n+5, 0);
  39.  
  40. dfs(1, Graph, vis, parent); // starts from source node
  41. return 0;
  42. }
Success #stdin #stdout 0s 5316KB
stdin
5 4
0 1
1 2
2 3
2 4
stdout
1
0
2
3
4