forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalSort.py
More file actions
38 lines (30 loc) · 841 Bytes
/
Copy pathTopologicalSort.py
File metadata and controls
38 lines (30 loc) · 841 Bytes
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
#!usr/bin/env python3
def Topological_Sort(vertices, edges):
def recursive_add(node):
if (node in ans):
return
if (edges[node] != []):
for edged_node in edges[node]:
recursive_add(edged_node)
ans.append(node)
# Memoizing this node, as all children have been covered
edges[node] = []
ans = []
while len(vertices) > 0:
node = vertices.pop()
recursive_add(node)
return ans[::-1]
def run():
# Keep in mind that there are mutiple possbile solutions for this given example
vertices = [5, 7, 3, 11, 2, 8, 9, 10]
edges = {
5: [11],
7: [11, 8],
3: [8, 10],
11: [2, 9, 10],
8: [9],
2: [],
9: [],
10: [],
}
print(Topological_Sort(vertices, edges))