File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include<iostream>
2
+ #include<list>
3
+ using namespace std;
4
+
5
+ // Graph class represents a directed graph
6
+ // using adjacency list representation
7
+ class Graph
8
+ {
9
+ int V;
10
+ list<int> *adj;
11
+ void DFSUtil(int v, bool visited[]);
12
+ public:
13
+ Graph(int V);
14
+ void addEdge(int v, int w);
15
+ void DFS(int v);
16
+ };
17
+
18
+ Graph::Graph(int V)
19
+ {
20
+ this->V = V;
21
+ adj = new list<int>[V];
22
+ }
23
+
24
+ void Graph::addEdge(int v, int w)
25
+ {
26
+ adj[v].push_back(w); // Add w to v’s list.
27
+ }
28
+
29
+ void Graph::DFSUtil(int v, bool visited[])
30
+ {
31
+ visited[v] = true;
32
+ cout << v << " ";
33
+ list<int>::iterator i;
34
+ for (i = adj[v].begin(); i != adj[v].end(); ++i)
35
+ if (!visited[*i])
36
+ DFSUtil(*i, visited);
37
+ }
38
+ void Graph::DFS(int v)
39
+ {
40
+ bool *visited = new bool[V];
41
+ for (int i = 0; i < V; i++)
42
+ visited[i] = false;
43
+ DFSUtil(v, visited);
44
+ }
45
+
46
+ int main()
47
+ {
48
+ Graph g(4);
49
+ g.addEdge(0, 1);
50
+ g.addEdge(0, 2);
51
+ g.addEdge(1, 2);
52
+ g.addEdge(2, 0);
53
+ g.addEdge(2, 3);
54
+ g.addEdge(3, 3);
55
+ cout << "Following is Depth First Traversal (starting from vertex 2)\n";
56
+ g.DFS(2);
57
+ return 0;
58
+ }
You can’t perform that action at this time.
0 commit comments