Skip to content

Commit 16b0d62

Browse files
committed
Add topological_sort.py
1 parent 7e35a83 commit 16b0d62

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

sorts/topological_sort.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# a
2+
# / \
3+
# b c
4+
# / \
5+
# d e
6+
edges = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
7+
vertices = ['a', 'b', 'c', 'd', 'e']
8+
9+
10+
def topological_sort(start, visited, sort):
11+
"""Perform topolical sort on a directed acyclic graph."""
12+
current = start
13+
# add current to visited
14+
visited.append(current)
15+
neighbors = edges[current]
16+
for neighbor in neighbors:
17+
# if neighbor not in visited, visit
18+
if neighbor not in visited:
19+
sort = topological_sort(neighbor, visited, sort)
20+
# if all neighbors visited add current to sort
21+
sort.append(current)
22+
# if all vertices haven't been visited select a new one to visit
23+
if len(visited) != len(vertices):
24+
for vertice in vertices:
25+
if vertice not in visited:
26+
sort = topological_sort(vertice, visited, sort)
27+
# return sort
28+
return sort
29+
30+
31+
sort = topological_sort('a', [], [])
32+
print(sort)

0 commit comments

Comments
 (0)