File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-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
+ class Graph
6
+ {
7
+ int numVertices;
8
+ list *adjLists;
9
+ bool *visited;
10
+
11
+ public:
12
+ Graph (int V);
13
+ void addEdge (int src, int dest);
14
+ void DFS (int vertex);
15
+ };
16
+
17
+ Graph::Graph (int vertices)
18
+ {
19
+ numVertices = vertices;
20
+ adjLists = new list[vertices];
21
+ visited = new bool [vertices];
22
+ }
23
+
24
+ void Graph::addEdge (int src, int dest)
25
+ {
26
+ adjLists[src].push_front (dest);
27
+ }
28
+
29
+ void Graph::DFS (int vertex)
30
+ {
31
+ visited[vertex] = true ;
32
+ list adjList = adjLists[vertex];
33
+
34
+ cout << vertex << " " ;
35
+
36
+ list::iterator i;
37
+ for (i = adjList.begin (); i != adjList.end (); ++i)
38
+ if (!visited[*i])
39
+ DFS (*i);
40
+ }
41
+
42
+ int main ()
43
+ {
44
+ Graph g (4 );
45
+ g.addEdge (0 , 1 );
46
+ g.addEdge (0 , 2 );
47
+ g.addEdge (1 , 2 );
48
+ g.addEdge (2 , 3 );
49
+ g.DFS (2 );
50
+
51
+ return 0 ;
52
+ }
You can’t perform that action at this time.
0 commit comments