forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Topological_Sort.cpp
96 lines (82 loc) · 1.73 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
/*
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;
// function to Create and represent a graph by storing data.
void createGraph()
{
int x, y;
adjList.resize(n);
for (int j = 0; j < n; j++)
{
cin >> x >> y;
adjList[x].push_back(y);
}
}
// A recursive function used by topoSortFun.
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);
}
// The function to do Topological Sort. It uses recursive topoSortFun().
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()
{
cout<<"Enter number of node you want to add: ";
cin >> n;
visited = new bool[n];
cout<<"Enter nodes of graph: ";
createGraph();
topoSort();
cout<<"Graph after topological sort: \n";
display();
}
/*
Test Case:
Input:
Enter number of node you want to add: 6
Enter nodes of graph:
5 2
5 0
4 0
4 1
2 3
3 1
Output:
Graph after topological sort:
5 4 2 3 1 0
Time Complexity: O(V + E) – where V is the number of vertices and E is the number of edges.
Space Complexity: O(V)
*/