Skip to content

Commit 9efddeb

Browse files
committed
Algorithm
1 parent 3028439 commit 9efddeb

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

python/sorting/topological_sort.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#topological sort
2+
3+
adjacent = {}
4+
Vertex = []
5+
parent = {}
6+
#stores the topological sort in reverse order.
7+
topological_sort = []
8+
9+
def initalizeVertex():
10+
n = int(input('Enter the no. of vertices.\n'))
11+
print("Enter the vertexes.")
12+
for i in range(n):
13+
vertex = input()
14+
Vertex.append(vertex)
15+
adjacent[vertex] = []
16+
17+
def initalizeDirectedEdges():
18+
n = int(input("Enter the no. of edges.\n"))
19+
print("Enter the space seperated edges.")
20+
for i in range(n):
21+
a,b = input().split()
22+
adjacent[a].append(b)
23+
24+
def showVertex():
25+
print('The vertexes are: ')
26+
print(vertex)
27+
print('\n')
28+
29+
def showEdges():
30+
print('The dictionary of edges are: ')
31+
print(adjacent)
32+
print('\n')
33+
34+
def t_sort(s):
35+
for neighbour in adjacent[s]:
36+
if neighbour not in parent.keys():
37+
parent[neighbour] = s
38+
#stack.append(neighbour)
39+
t_sort(neighbour)
40+
topological_sort.append(s)
41+
42+
43+
# Driver Code
44+
45+
initalizeVertex()
46+
initalizeDirectedEdges()
47+
#showVertex()
48+
#showEdges()
49+
print('Implementing Topological Sort.')
50+
#for a well connected grapgh, we don't need the below for loop.
51+
#dfs(starting_vertex) will give correct result.
52+
#the below for loop is used for unconnected graphs.
53+
for v in Vertex:
54+
if v not in parent.keys():
55+
parent[v] = None
56+
t_sort(v)
57+
58+
print('Topological sort order is: ')
59+
print(topological_sort[::-1])

0 commit comments

Comments
 (0)