forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopological_sort.cpp
99 lines (84 loc) · 1.48 KB
/
Topological_sort.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering
of vertices such that for every directed edge uv, vertex u comes before v in
the ordering. Topological Sorting for a graph is not possible if the graph is
not a DAG.
*/
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> adjList;
stack<int> s;
bool *visited;
// Number of Test Cases (Vertices)
int n;
void createGraph()
{
int x, y;
adjList.resize(n);
for (int j = 0; j < n; j++)
{
cin >> x >> y;
adjList[x].push_back(y);
}
}
void topoSortFun(int i)
{
visited[i] = true;
for (int j = 0; j < adjList[i].size(); j++)
{
int key = adjList[i][j];
if (!visited[key])
topoSortFun(key);
}
s.push(i);
}
void topoSort()
{
memset(visited, false, sizeof(visited));
for (int i = 0; i < n; i++)
{
if (!visited[i])
topoSortFun(i);
}
}
void display()
{
for (int i = 0; i < n; i++)
{
cout << s.top() << " ";
s.pop();
}
}
int main()
{
cin >> n;
visited = new bool[n];
createGraph();
topoSort();
display();
}
/*
Test Case:
Input 1 :
6
5 2
5 0
4 0
4 1
2 3
3 1
Output 1 :
5 4 2 3 1 0
Input 2 :
6
4 2
5 1
4 0
3 1
1 3
3 2
Output 2 :
5 4 1 3 2 0
Time Complexity: O(V + E) – where V is the number of vertices and E is the number of edges.
Space Complexity: O(V)
*/