Advertisement
Guest User

Untitled

a guest
May 4th, 2015
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include<iostream>
  2. #include <list>
  3. using namespace std;
  4.  
  5. class Graph
  6. {
  7.     int V;
  8.     list<int> *adj;
  9.     void DFSUtil(int v, bool visited[]);
  10. public:
  11.     Graph(int V);
  12.     void addEdge(int v, int w);
  13.     void DFS();
  14. };
  15.  
  16. Graph::Graph(int V)
  17. {
  18.     this->V = V;
  19.     adj = new list<int>[V];
  20. }
  21.  
  22. void Graph::addEdge(int v, int w)
  23. {
  24.     adj[v].push_back(w);
  25. }
  26.  
  27. void Graph::DFSUtil(int v, bool visited[])
  28. {
  29.     visited[v] = true;
  30.     cout << v << " ";
  31.     list<int>::iterator i;
  32.     for(i = adj[v].begin(); i != adj[v].end(); ++i)
  33.         if(!visited[*i])
  34.             DFSUtil(*i, visited);
  35. }
  36.  
  37. void Graph::DFS()
  38. {
  39.     bool *visited = new bool[V];
  40.     for(int i = 0; i < V; i++)
  41.         visited[i] = false;
  42.     for(int i = 0; i < V; i++)
  43.         if(visited[i] == false)
  44.             DFSUtil(i, visited);
  45. }
  46.  
  47. int main()
  48. {
  49.     Graph g(4);
  50.     g.addEdge(0, 1);
  51.     g.addEdge(0, 2);
  52.     g.addEdge(1, 2);
  53.     g.addEdge(2, 0);
  54.     g.addEdge(2, 3);
  55.     g.addEdge(3, 3);
  56.     g.DFS();
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement