2019-07-01 08:10:18 +00:00
|
|
|
"""Topological Sort."""
|
|
|
|
|
2017-06-21 23:11:31 +00:00
|
|
|
# a
|
|
|
|
# / \
|
|
|
|
# b c
|
|
|
|
# / \
|
|
|
|
# d e
|
2019-10-05 05:14:13 +00:00
|
|
|
edges = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []}
|
|
|
|
vertices = ["a", "b", "c", "d", "e"]
|
2017-06-21 23:11:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
def topological_sort(start, visited, sort):
|
2021-10-04 04:07:58 +00:00
|
|
|
"""Perform topological sort on a directed acyclic graph."""
|
2017-06-21 23:11:31 +00:00
|
|
|
current = start
|
|
|
|
# add current to visited
|
|
|
|
visited.append(current)
|
|
|
|
neighbors = edges[current]
|
|
|
|
for neighbor in neighbors:
|
|
|
|
# if neighbor not in visited, visit
|
|
|
|
if neighbor not in visited:
|
|
|
|
sort = topological_sort(neighbor, visited, sort)
|
|
|
|
# if all neighbors visited add current to sort
|
|
|
|
sort.append(current)
|
|
|
|
# if all vertices haven't been visited select a new one to visit
|
|
|
|
if len(visited) != len(vertices):
|
|
|
|
for vertice in vertices:
|
|
|
|
if vertice not in visited:
|
|
|
|
sort = topological_sort(vertice, visited, sort)
|
|
|
|
# return sort
|
|
|
|
return sort
|
|
|
|
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
sort = topological_sort("a", [], [])
|
2019-05-25 13:41:24 +00:00
|
|
|
print(sort)
|