This repository has been archived by the owner on Nov 21, 2020. It is now read-only.
forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Depth_First_Search.cpp
93 lines (73 loc) · 1.78 KB
/
Depth_First_Search.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Graph
{
int numberVertex;
vector <int> *adjacency;
public:
// Constructor to initialise graph
Graph(int numberVertex)
{
this->numberVertex = numberVertex;
adjacency = new vector <int> [numberVertex];
}
// Function to add edge between source and destination
void addEdge(int source, int destination)
{
adjacency[source].push_back(destination);
}
// Function to perform Depth First Search
void dfs(int starting);
};
void Graph::dfs(int starting)
{
bool visited[numberVertex];
for(int i = 0; i < numberVertex; i++)
visited[i] = false;
stack <int> stack_vertex;
visited[starting] = true;
stack_vertex.push(starting);
vector <int> :: iterator it;
while(!stack_vertex.empty())
{
starting = stack_vertex.top();
cout << starting << " ";
stack_vertex.pop();
for(it = adjacency[starting].begin(); it != adjacency[starting].end(); ++it)
{
if(!visited[*it])
{
visited[*it] = true;
stack_vertex.push(*it);
}
}
}
}
int main()
{
// Number of vertices is 8
Graph graph(8);
// Create edges between vertices
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(1, 4);
graph.addEdge(2, 0);
graph.addEdge(2, 3);
graph.addEdge(3, 3);
graph.addEdge(3, 6);
graph.addEdge(4, 0);
graph.addEdge(4, 5);
graph.addEdge(5, 6);
graph.addEdge(5, 7);
graph.addEdge(6, 2);
graph.addEdge(7, 3);
cout << "Depth First Traversal is : ";
graph.dfs(0);
return 0;
}
/* Output
Depth First Traversal is : 0 2 3 6 1 4 5 7
*/