-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathTopologicalSortusingDFS.cpp
60 lines (55 loc) · 1.16 KB
/
TopologicalSortusingDFS.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
#include <bits/stdc++.h>
using namespace std;
class Graph {
private:
map<char,list<int>> mp;
public:
void add_edge(char a, char b)
{
mp[a].push_back(b);
}
void Topological_sort()
{
unordered_map<char,bool> visited;
list<char> ordering;
for(auto x:mp)
{
visited[x.first]=false;
}
for(auto x:mp)
{
if(!visited[x.first])
{
dfs_helper(visited,ordering,x.first);
}
}
for(auto node : ordering)
{
cout<<node<<" ";
}
}
void dfs_helper(unordered_map<char,bool>& visited, list<char>& ordering, char src)
{
visited[src]=true;
for(auto nbr:mp[src])
{
if(!visited[nbr])
{
dfs_helper(visited,ordering,nbr);
visited[nbr]=true;
}
}
ordering.push_front(src);
}
};
int main()
{
Graph g;
g.add_edge('z','x');
g.add_edge('x','a');
g.add_edge('x','b');
g.add_edge('x','c');
g.add_edge('z','y');
g.add_edge('y','a');
g.Topological_sort();
}