forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode12.cpp
More file actions
75 lines (65 loc) · 1.65 KB
/
code12.cpp
File metadata and controls
75 lines (65 loc) · 1.65 KB
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
// Topological Sort -> DFS
// In DFS type approach we first go till end where there are no more adjacents left that means we can then push them
// and above that we will push vertex which are parents and we will do it with recursion.
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int inf = 1e9 + 7;
void add_edge(vector<int> vec[], int u, int v)
{
vec[u].push_back(v);
}
void topo_sort(vector<int> vec[], vector<bool> &visited, int source, stack<int> &s)
{
cout<<"source: "<<source<<endl;
visited[source] = true;
for (int i = 0; i < vec[source].size(); i++)
{
int adjacent = vec[source][i];
if (visited[adjacent] == false)
{
topo_sort(vec, visited, adjacent, s);
}
}
s.push(source);
return;
}
void topo_rec(vector<int> vec[], int v)
{
vector<bool> visited(v, false);
stack<int> s;
for (int i = 0; i < v; i++)
{
if (visited[i] == false)
{
topo_sort(vec, visited, i, s);
}
}
while(s.size() > 0) {
int curr = s.top();
s.pop();
cout<<curr << " ";
}
return;
}
int main()
{
int v;
v = 4;
vector<int> vec[v];
// adding edges from this point
// add_edge(vec, 0, 1);
// add_edge(vec, 0, 3);
// add_edge(vec, 1, 2);
// add_edge(vec, 2, 4);
// add_edge(vec, 3, 1);
// add_edge(vec, 3, 4);
add_edge(vec, 0, 1);
// add_edge(vec, 0, 3);
add_edge(vec, 1, 2);
add_edge(vec, 1, 3);
add_edge(vec, 3, 2);
// add_edge(vec, 3, 4);
topo_rec(vec, v);
return 0;
}