-
Notifications
You must be signed in to change notification settings - Fork 1
/
DFS.cpp
79 lines (72 loc) · 1.22 KB
/
DFS.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
#include<bits/stdc++.h>
using namespace std;
class Graph
{
private:
int *start_time;
int *finish_time;
int vertices;
bool *visited;
list<int> *adj;
int time;
public:
Graph(int);
void addedge(int,int);
void DFS(int);
void Time();
};
Graph::Graph(int v)
{
this->vertices=v;
start_time = new int[v];
finish_time = new int[v];
adj = new list<int>[v];
visited= new bool[v];
for(int i=0;i<v;i++)
{
visited[i]=false;
}
time=0;
}
void Graph::addedge(int u,int v)
{
adj[u].emplace_back(v);
}
void Graph::DFS(int source)
{
time+=1;
start_time[source]=time;
visited[source]=true;
cout<<source<<" ";
//cout<<"vertex"<<source<<"Start time"<<start_time[source]<<" ";
for(auto i=adj[source].begin();i!=adj[source].end();++i)
{
if(visited[*i]==false)
DFS(*i);
}
time++;
finish_time[source]=time;
//cout<<"Vertex "<<source<<" end time "<<finish_time[source]<<endl;
}
int main()
{
int v;
cout<<"Enter the number of vertices\n";
cin>>v;
int edges;
cout<<"number of edges\t";
cin>>edges;
Graph g(v);
for(int i=0;i<edges;i++)
{
int a,b;
cin>>a>>b;
g.addedge(a,b);
}
cout<<"Enter the source vertex:";
int source;
cin>>source;
cout<<"The DFS starting with "<<source<<" is\n";
g.DFS(source);
cout<<endl;
}