fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void DFS(int node, vector<vector<int>>& g, vector<int>& visited, vector<int>& parent){
  5.  
  6. cout << node << '\n';
  7. visited[node] = 1;
  8.  
  9. for (auto &i : g[node]){
  10. if(visited[i] == 0){
  11. parent[i] = node;
  12. DFS(i, g, visited, parent);
  13. }
  14. }
  15. }
  16.  
  17. int main() {
  18.  
  19. int n,e;
  20. cin >> n >> e;
  21.  
  22. vector<vector<int>> g(n+5);
  23.  
  24. for (int i = 0; i < e; i++){
  25. int a, b;
  26. cin >> a >> b;
  27. g[a].push_back(b);
  28. g[b].push_back(a);
  29. }
  30.  
  31. int source;
  32. cin >> source;
  33.  
  34. vector<int> visited(n+5, 0);
  35. vector<int> parent(n+5, 0);
  36.  
  37. DFS(source, g, visited, parent);
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 5316KB
stdin
5 4
1 2
1 4
2 3
4 5
1
stdout
1
2
3
4
5