Skip to content

Commit fa42d78

Browse files
authored
Merge pull request AllAlgorithms#11 from underscoreorcus/master
DFS added under Graphs
2 parents 25f55c2 + d0f9f7d commit fa42d78

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

graphs/dfs.cpp

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

0 commit comments

Comments
 (0)