forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Topological_Sort.py
66 lines (50 loc) · 1.51 KB
/
Topological_Sort.py
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
class Graph:
"""
* Creates a adjaceny list for a graph
* Implements a function for topological sorting
"""
def __init__(self, no_vertices):
"""
Initialises an empty adjaceny list (list of lists)
"""
self.vertices = no_vertices
self.adjlist = [[] for i in xrange(0, no_vertices)]
def add_edge(self, vert1, vert2):
"""
Creates an edge between two vertices
"""
self.adjlist[vert1].append(vert2)
def topological_sort_util(self, i, stack, visited):
"""
Utility function for topological sort
"""
visited[i] = True
for node in self.adjlist[i]:
if not visited[node]:
self.topological_sort_util(node, stack, visited)
stack.append(i)
def topological_sort(self):
"""
Implements topological sort (DFS based approach)
"""
stack = []
visited = [False for i in xrange(0, self.vertices)]
for i in xrange(0, self.vertices):
if not visited[i]:
self.topological_sort_util(i, stack, visited)
print "Topological Sort : ",
while len(stack) > 0:
print stack.pop(),
def main():
graph = Graph(6)
graph.add_edge(5, 2);
graph.add_edge(5, 0);
graph.add_edge(4, 0);
graph.add_edge(4, 1);
graph.add_edge(2, 3);
graph.add_edge(3, 1);
graph.topological_sort()
if __name__ == "__main__":
main()
#OUTPUT
#Topological Sort : 5 4 2 3 1 0