-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoposort using dfs.cpp
More file actions
59 lines (54 loc) · 825 Bytes
/
toposort using dfs.cpp
File metadata and controls
59 lines (54 loc) · 825 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
#include<bits/stdc++.h>
using namespace std;
template<typename T>
class graph{
map<int,list<T> >l;
public:
void eddedge(int x,int y){
l[x].push_back(y); //directed graph
}
void dfs_helper(map<T,bool>&vis,T src,stack<T> s)
{
vis[src]=true;
for(auto p:l[src]){
if(!vis[p])
{
dfs_helper(vis,p,s);
}
}
s.push(src);
}
void dfs_topo(){
map<T,bool>vis;
stack<T>s;
for(auto d:l)
{
T node=d.first;
vis[node]=false;
}
for(auto d:l){
T nbr=d.first;
if(!vis[nbr])
{
dfs_helper(vis,nbr,s);
}
}
while(!s.empty())
{
T r=s.top();
cout<<r<<" ";
s.pop();
}
}
};
int main()
{
graph<int>g;
g.eddedge(5,2);
g.eddedge(5,0);
g.eddedge(4,0);
g.eddedge(4,1);
g.eddedge(2,3);
g.eddedge(3,1);
g.dfs_topo();
}