-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathDFS.cpp
More file actions
83 lines (57 loc) · 971 Bytes
/
Copy pathDFS.cpp
File metadata and controls
83 lines (57 loc) · 971 Bytes
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
#include<iostream>
#include<list>
#include<queue>
#include<map>
#include<vector>
using namespace std;
//Adjacency list using array of list
class Graph{
int V;
list<int> *l;
public:
Graph(int a)
{
V=a;
l=new list<int>[a];
}
void addnode(int u,int v)
{
l[u].push_back(v);
//l[v].push_back(u);
}
void DFS_helper(int i,vector<int>&final,vector<int> &visited)
{
if(visited[i]!=1)
{
visited[i]=1;
final.push_back(i);
for(auto a:l[i])
DFS_helper(a,final,visited);
}
}
void DFS()
{
vector<int> visited(V,0); //to keep track of visited vertex
vector<int> final; //to store the final output
for(int i=0;i<V;i++)
{
DFS_helper(i,final,visited);
}
for(auto a:final)
cout<<a<<" ";
}
};
int main()
{
int e,v,a,b;
cin>>v>>e;
Graph g(v);
while(e--)
{
cin>>a>>b;
g.addnode(a,b);
}
//g.display();
g.DFS();
return 0;
}