fork download
  1. #include <iostream>
  2. #include <list>
  3. using namespace std;
  4.  
  5. struct Graph
  6. {
  7. int V;
  8. list <int> *adj;
  9.  
  10. Graph(int _V)
  11. {
  12. V = _V;
  13. adj = new list <int> [V];
  14. }
  15.  
  16. void addEdge(int v, int w)
  17. {
  18. adj[v].push_back(w);
  19. }
  20.  
  21. void DFSUtil(int v, bool visited[])
  22. {
  23. visited[v] = true;
  24. cout<<v<<" ";
  25.  
  26. for(auto i: adj[v])
  27. if(!visited[i])
  28. DFSUtil(i, visited);
  29. }
  30.  
  31. void DFS(int v)
  32. {
  33. bool *visited = new bool[V];
  34. for(int i = 0; i < V; i++)
  35. visited[i] = false;
  36.  
  37. DFSUtil(v, visited);
  38. }
  39. };
  40.  
  41. int main()
  42. {
  43. Graph g(4);
  44.  
  45. g.addEdge(0, 1);
  46. g.addEdge(0, 2);
  47. g.addEdge(1, 2);
  48. g.addEdge(2, 0);
  49. g.addEdge(2, 3);
  50. g.addEdge(3, 3);
  51.  
  52. cout << "Following is Depth First Traversal (starting from vertex 2) \n";
  53. g.DFS(2);
  54.  
  55. return 0;
  56. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
Following is Depth First Traversal (starting from vertex 2) 
2 0 1 3