fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void DFS(int source, vector<int> adjList[], vector<int> &visited, vector<int> &parent){
  5. visited[source]=1;
  6. cout<<source<<" ";
  7. for(auto adjNode : adjList[source]){
  8. if(!visited[adjNode]){
  9. parent[adjNode]=source;
  10. DFS(adjNode, adjList, visited, parent);
  11. }
  12. }
  13. }
  14.  
  15. int main() {
  16. int n,m;
  17. cin>>n>>m;
  18. vector<int> adjList[n];
  19. vector<int> parent(n, 0);
  20. for(int i=0;i<m;i++){
  21. int x,y;
  22. cin>>x>>y;
  23. adjList[x].push_back(y);
  24. adjList[y].push_back(x);
  25. }
  26. int source=0;
  27. vector<int> visited(n, 0);
  28. for (int i=0;i<n;i++) {
  29. if (!visited[i]) {
  30. DFS(i, adjList, visited, parent);
  31. }
  32. }
  33. return 0;
  34. }
Success #stdin #stdout 0s 5324KB
stdin
6 5
0 1
1 2
3 4
4 5
5 3
stdout
0 1 2 3 4 5