fork download
  1. /*
  2. ================== DEPTH FIRST SEARCH ==================
  3. */
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. void DFS ( int node, vector<int>* G, vector<bool>& visited ){
  8.  
  9. // print the visited node
  10. cout << node << " ";
  11. // mark the current node as visited
  12. visited[node] = true;
  13.  
  14. // for all the adjacent nodes of the current node
  15. for( int adj : G[node] ){
  16. // if the adjacent node is not already visited then visit it
  17. if( !visited[adj] )
  18. DFS( adj, G, visited );
  19. }
  20. }
  21.  
  22. int main() {
  23.  
  24. // V = number of vertices, E = number of edges
  25. int V, E;
  26. cin >> V >> E;
  27.  
  28. // adjacency list
  29. vector<int>* G = new vector<int>[V];
  30. vector<bool> visited(V, false);
  31.  
  32. int p,q;
  33. while(E--){
  34. cin>>p>>q;
  35. // As it is an undirected graph we are pushing two edges between one pair of vertices
  36. G[p].push_back(q);
  37. G[q].push_back(p);
  38. }
  39.  
  40. // Visiting all the Verices once in Depth First Manner
  41. for( int i=0 ; i<V ; i++ ){
  42. if( !visited[i] )
  43. DFS(i, G, visited);
  44. }
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 4220KB
stdin
6 7
0 1
0 3
0 4
1 5
2 4
3 4
4 5
stdout
0 1 5 4 2 3