-
Notifications
You must be signed in to change notification settings - Fork 0
/
topological_sort.py
59 lines (44 loc) · 1.41 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
##############################################################
#
# Algorithme of topological sort wich is available only for
# Directed Acyclic Graph (where there is no cyclic path i.e
# there is no indegree=0)
#
##############################################################
from queue import Queue
from graph import *
def topological_sort(graph):
queue = Queue()
indegreeMap = {}
for i in range(graph.numVertices):
indegreeMap[i] = graph.get_indegree(i)
# Queue all nodes wich have no dependencies i.e
# no edge coming
if indegreeMap[i] == 0:
queue.put(i)
sortedList = []
while not queue.empty():
vertex = queue.get()
sortedList.append(vertex)
for v in graph.get_adjacent_vertices(vertex):
indegreeMap[v] = indegreeMap[v] - 1
if indegreeMap[v] == 0:
queue.put(v)
if len(sortedList) != graph.numVertices:
raise ValueError(
"This graph has a cycle !!! \n => topological sort is IMPOSSIBLE")
print(sortedList)
# test implementation
g = AdjacencyMatrixGraph(9, directed=True)
g.add_edge(0, 1)
g.add_edge(1, 2)
# g.add_edge(2, 0) # with this edge the graph is a directed CYCLIC graph, so topological_sort is impossible
g.add_edge(2, 7)
g.add_edge(2, 4)
g.add_edge(2, 3)
g.add_edge(1, 5)
g.add_edge(5, 6)
g.add_edge(3, 6)
g.add_edge(3, 4)
g.add_edge(6, 8)
topological_sort(g)