|
| 1 | +#include<iostream> |
| 2 | +#include <list> |
| 3 | + |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +// This class represents a directed graph using |
| 7 | +// adjacency list representation |
| 8 | +class Graph |
| 9 | +{ |
| 10 | + int V; // No. of vertices |
| 11 | + |
| 12 | + // Pointer to an array containing adjacency |
| 13 | + // lists |
| 14 | + list<int> *adj; |
| 15 | + |
| 16 | + // A recursive function used by DFS |
| 17 | + void DFSUtil(int s, bool visited[]); |
| 18 | + |
| 19 | +public: |
| 20 | + Graph(int V); // Constructor |
| 21 | + |
| 22 | + // function to add an edge to graph |
| 23 | + void addEdge(int v, int w); |
| 24 | + |
| 25 | + // prints DFS traversal from a given source s |
| 26 | + void DFS(int s); |
| 27 | +}; |
| 28 | + |
| 29 | +Graph::Graph(int V) |
| 30 | +{ |
| 31 | + this->V = V; |
| 32 | + adj = new list<int>[V]; |
| 33 | +} |
| 34 | + |
| 35 | +void Graph::addEdge(int v, int w) |
| 36 | +{ |
| 37 | + adj[v].push_back(w); // Add w to v’s list. |
| 38 | +} |
| 39 | + |
| 40 | +void Graph::DFSUtil(int s, bool visited[]) |
| 41 | +{ |
| 42 | + // Mark the current node as visited and |
| 43 | + // print it |
| 44 | + visited[s] = true; |
| 45 | + cout << s << " "; |
| 46 | + |
| 47 | + // Recur for all the vertices adjacent |
| 48 | + // to this vertex |
| 49 | + list<int>::iterator i; |
| 50 | + for (i = adj[s].begin(); i != adj[s].end(); ++i) |
| 51 | + if (!visited[*i]) |
| 52 | + DFSUtil(*i, visited); |
| 53 | +} |
| 54 | + |
| 55 | +// DFS traversal of the vertices reachable from s. |
| 56 | +// It uses recursive DFSUtil() |
| 57 | +void Graph::DFS(int s) |
| 58 | +{ |
| 59 | + // Mark all the vertices as not visited |
| 60 | + bool *visited = new bool[V]; |
| 61 | + for (int i = 0; i < V; i++) |
| 62 | + visited[i] = false; |
| 63 | + |
| 64 | + // Call the recursive helper function |
| 65 | + // to print DFS traversal |
| 66 | + DFSUtil(s, visited); |
| 67 | +} |
| 68 | + |
| 69 | +// Driver program to test methods of graph class |
| 70 | +int main() |
| 71 | +{ |
| 72 | + // Create a graph given in the above diagram |
| 73 | + Graph g(4); |
| 74 | + g.addEdge(0, 1); |
| 75 | + g.addEdge(0, 2); |
| 76 | + g.addEdge(1, 2); |
| 77 | + g.addEdge(2, 0); |
| 78 | + g.addEdge(2, 3); |
| 79 | + g.addEdge(3, 3); |
| 80 | + |
| 81 | + cout << "Following is Depth First Traversal" |
| 82 | + " (starting from vertex 2) \n"; |
| 83 | + g.DFS(2); |
| 84 | + |
| 85 | + return 0; |
| 86 | +} |
0 commit comments