Skip to content

Commit 03128c7

Browse files
Merge pull request #376 from sonalimahajan12/sonali
Recursive DFS in CPP
2 parents 1169933 + c5571f1 commit 03128c7

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Graph Traversal/DFS/dfs_recursive.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
}

0 commit comments

Comments
 (0)