-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopologicalsort.cpp
77 lines (68 loc) · 1.11 KB
/
topologicalsort.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
#include<iostream>
#include<list>
#include<stack>
using namespace std;
class graph
{public:
int v;
list<int> *array;
list<int> p; //keeps the topological order
stack <int> s; //to maintain dfs
bool *visited;
graph(int);
void add(int src,int des);
void dfs(int);
void topologicalsort(int);
};
graph::graph(int a)
{
v=a;
array=new list<int>[v];
visited=new bool[v+1];
for(int i=0;i<=v;i++)
visited[i]=false;
}
void graph::add(int src,int des)
{
array[src].push_back(des);
}
void graph::topologicalsort(int l)
{
dfs(l);
while(!p.empty())
{
cout << p.front() << " ";
p.pop_front();
}
}
void graph::dfs(int v)
{
s.push(v);
visited[v]=true;
list<int>::iterator i;
while(!s.empty())
{
int now=s.top();
p.push_back(now);
s.pop();
for(i=array[now].begin();i!=array[now].end();i++)
{
if(visited[*i]==false)
dfs(*i);
}
}
}
int main()
{
graph g(6);
//g.add(5, 2);
//g.add(5, 0);
g.add(4, 2);
g.add(4, 1);
g.add(3, 2);
g.add(3, 1);
cout << "Following is a Topological Sort of the given graph ";
g.topologicalsort(4);
//g.print();
return 0;
}