8000 Added topological sort. · pythonpeixun/practice-python@9f1ce14 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9f1ce14

Browse files
committed
Added topological sort.
1 parent b4437a9 commit 9f1ce14

File tree

1 file changed

+59
-1
lines changed

1 file changed

+59
-1
lines changed

graphs/directed_graph_list.py

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def contains_cycle(self):
111111
statuses[v] = STATUS_FINISHED
112112
else:
113113
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
115115

116116
for u in self.get_edge(v):
117117
if u in statuses:
@@ -126,6 +126,40 @@ def contains_cycle(self):
126126

127127
return contains_cycle
128128

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+
129163

130164
def main():
131165
dg = DirectedGraph()
@@ -151,6 +185,30 @@ def main():
151185

152186
print("Contains a cycle: ", dg.contains_cycle())
153187

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+
154212

155213
if __name__ == "__main__":
156214
main()

0 commit comments

Comments
 (0)
0