@@ -111,7 +111,7 @@ def contains_cycle(self):
111
111
statuses [v ] = STATUS_FINISHED
112
112
else :
113
113
statuses [v ] = STATUS_STARTED
114
- to_visit .append (v ) # add to stack to signal vertex has finished DFS
114
+ to_visit .append (v ) # add to stack again to signal vertex has finished DFS
115
115
116
116
for u in self .get_edge (v ):
117
117
if u in statuses :
@@ -126,6 +126,40 @@ def contains_cycle(self):
126
126
127
127
return contains_cycle
128
128
129
+ def topological_sort (self ):
130
+ """
131
+ Determines the priority of vertices to be visited.
132
+ :return:
133
+ """
134
+ STATUS_STARTED = 1
135
+ STATUS_FINISHED = 2
136
+ order = []
137
+ statuses = {}
138
+
139
+ assert (not self .contains_cycle ())
140
+
141
+ for vertex in self .get_vertex ():
142
+ to_visit = [vertex ]
143
+
144
+ while to_visit :
145
+ v = to_visit .pop ()
146
+
147
+ if v in statuses :
148
+ if statuses [v ] == STATUS_STARTED :
149
+ statuses [v ] = STATUS_FINISHED
150
+ order .append (v )
151
+ else :
152
+ statuses [v ] = STATUS_STARTED
153
+ to_visit .append (v ) # add to stack again to signal vertex has finished DFS
154
+
155
+ for u in self .get_edge (v ):
156
+ if u not in statuses :
157
+ to_visit .append (u )
158
+
159
+ order .reverse ()
160
+
161
+ return order
162
+
129
163
130
164
def main ():
131
165
dg = DirectedGraph ()
@@ -151,6 +185,30 @@ def main():
151
185
152
186
print ("Contains a cycle: " , dg .contains_cycle ())
153
187
188
+ print ("Topological sort" , dg .topological_sort ())
189
+
190
+ # another with edges added out of order
191
+ dg_small = DirectedGraph ()
192
+ dg_small .add_edge (2 , 1 )
193
+ dg_small .add_edge (4 , 5 )
194
+ dg_small .add_edge (0 , 1 )
195
+ dg_small .add_edge (1 , 4 )
196
+ dg_small .add_edge (1 , 3 )
197
+
198
+ print ("Topological sort" , dg_small .topological_sort ())
199
+
200
+ # making edges out of order with random~ish vertex numbers
201
+ dg_other = DirectedGraph ()
202
+ dg_other .add_edge (3 , 11 )
203
+ dg_other .add_edge (5 , 2 )
204
+ dg_other .add_edge (2 , 4 )
205
+ dg_other .add_edge (2 , 7 )
206
+ dg_other .add_edge (8 , 11 )
207
+ dg_other .add_edge (4 , 7 )
208
+ dg_other .add_edge (7 , 8 )
209
+
210
+ print ("Topological sort" , dg_other .topological_sort ())
211
+
154
212
155
213
if __name__ == "__main__" :
156
214
main ()
0 commit comments