-
Notifications
You must be signed in to change notification settings - Fork 0
/
15_1_TopologicalSort.py
56 lines (42 loc) · 1.08 KB
/
15_1_TopologicalSort.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
#Python
def importData():
file = open('test.txt', 'r')
m=file.readlines()
list=[]
graph={}
for i in m:
i=i.strip()
node,vertex=i.split("->")
vertexList=vertex.split(",")
node=node.strip()
graph[node]=[]
for k in vertexList:
k=k.strip()
graph[node].append(k)
for node in graph.keys():
for val in graph[node]:
if val not in graph:
graph[val]={}
return graph
def order(node, visit, stack):
visit[node]=True
for i in graph[node]:
if visit[i] == None:
order(i,visit,stack)
stack.append(node)
def topo(graph):
visit={}
for node in graph:
visit[node]=None
stack=[]
for node in graph:
if visit[node] == None:
order(node,visit,stack)
return stack
def output(stack):
file = open("output.txt", "w+")
file.write(', '.join(stack[::-1]))
file.close()
graph=importData()
stack=topo(graph)
output(stack)