-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopological_Sort.cpp
146 lines (131 loc) · 2.68 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <iostream.h>
#include <conio.h>
#include <timer.h>
#include <stdlib.h>
class Stack
{
int top;
int a[800];
public :
Stack()
{
top = -1;
for(int i = 0;i < 800;i++) a[i] = 0;
}
void push(int ele)
{
a[++top] = ele;
}
int getTop()
{
return a[top];
}
void pop()
{
top--;
}
int isEmpty()
{
return(top == -1);
}
void clear()
{
top = -1;
}
};
class Graph
{
int *visited;
int nodes,sides;
int **edges;
Stack stck;
public :
Graph()
{
nodes = sides = 0;
}
void input()
{
cout << "\nGive the number of nodes : ";cin >> nodes;
visited = new int [nodes];
*edges = new int [nodes];
for(int i = 0;i < nodes;i++) edges[i] = new int [nodes];
for(int row = 0;row < nodes;row++)
for(int col = 0;col < nodes;col++)
visited[row] = edges[row][col] = 0;
cout << "\nGive the number of edges : ";cin >> sides;
while(sides--)
{
int start,end;
cout << "From : ";cin >> start;
cout << "To : ";cin >> end;cout << "\n";
edges[start - 1][end - 1] = 1;
}
}
void dfs(int source)
{
visited[source] = 1;
for(int i = 0;i < nodes;i++)
if((edges[source][i] > 0) && !visited[i])
dfs(i);
stck.push(source + 1);
}
void topo_sort()
{
for(int i = 0;i < nodes;i++)
if(!visited[i])
dfs(i);
}
void print()
{
cout << "\nThe topologically sorted order is : \n";
cout << "\n[ " << stck.getTop();stck.pop();
while(!stck.isEmpty())
{
cout << " , " << stck.getTop();
stck.pop();
}
cout << " ]\n";
}
void randomize()
{
Timer t;
for(int i = 1;i < 20;i++)
{
cout << "\nFor operation : " << i;
nodes = i;
//general initializations
visited = new int [nodes];
*edges = new int [nodes];
for(int i = 0;i < nodes;i++) edges[i] = new int [nodes];
for(int row = 0;row < nodes;row++)
for(int col = 0;col < nodes;col++)
{ visited[row] = 0;
edges[row][col] = -1;
}
//-----------------------
for(int k = 0;k < nodes;k++)
for(int l = 0;l < nodes;l++)
{
if(edges[k][l] != -1) continue;
edges[k][l] = rand() % 2;
edges[l][k] = 0;
}
t.start();topo_sort();t.stop();stck.clear();
cout << " time taken is : " << t.time() << " seconds";
}
}
};
int main()
{
clrscr();
Timer t;
Graph G;
G.input();
t.start();G.topo_sort();t.stop();
G.print();
cout << "\nTime taken for this is : " << t.time() << " seconds\n";
//G.randomize(); //uncomment this only for bulk operation(by commenting from G.input() to just before G.randomize())
getch();
return 0;
}