-
Notifications
You must be signed in to change notification settings - Fork 1k
/
topological_sort.py
62 lines (52 loc) · 1.54 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
#topological sort
#a key-value pair represent a vertex and all it's outward edges.
adjacent = {}
#stores the list of vertex.
Vertex = []
# a key-value pair represents a vertex and its parent.
parent = {}
#stores the topological sort in reverse order.
topological_sort = []
def initalizeVertex():
n = int(input('Enter the no. of vertices.\n'))
print("Enter the vertexes.")
for i in range(n):
vertex = input()
Vertex.append(vertex)
adjacent[vertex] = []
def initalizeDirectedEdges():
n = int(input("Enter the no. of edges.\n"))
print("Enter the space seperated edges.")
for i in range(n):
a,b = input().split()
adjacent[a].append(b)
def showVertex():
print('The vertexes are: ')
print(vertex)
print('\n')
def showEdges():
print('The dictionary of edges are: ')
print(adjacent)
print('\n')
def t_sort(s):
for neighbour in adjacent[s]:
if neighbour not in parent.keys():
parent[neighbour] = s
#stack.append(neighbour)
t_sort(neighbour)
topological_sort.append(s)
# program starts here
initalizeVertex()
initalizeDirectedEdges()
#showVertex()
#showEdges()
print('Implementing Topological Sort.')
#for a well connected grapgh, we don't need the below for loop.
#dfs(starting_vertex) will give correct result.
#the below for loop is used for unconnected graphs.
for v in Vertex:
if v not in parent.keys():
parent[v] = None
t_sort(v)
print('Topological sort order is: ')
print(topological_sort[::-1])