Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 3ceccfb

Browse files
committedOct 26, 2024
Fixed
1 parent 03a4251 commit 3ceccfb

File tree

1 file changed

+4
-23
lines changed

1 file changed

+4
-23
lines changed
 

‎sorts/topological_sort.py

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
1-
"""Topological Sort."""
2-
3-
# a
4-
# / \
5-
# b c
6-
# / \
7-
# d e
81
edges: dict[str, list[str]] = {
92
"a": ["c", "b"],
103
"b": ["d", "e"],
@@ -14,28 +7,16 @@
147
}
158
vertices: list[str] = ["a", "b", "c", "d", "e"]
169

17-
1810
def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
19-
"""Perform topological sort on a directed acyclic graph."""
11+
visited.append(start)
2012
current = start
21-
# add current to visited
22-
visited.append(current)
23-
neighbors = edges[current]
24-
for neighbor in neighbors:
25-
# if neighbor not in visited, visit
13+
for neighbor in edges[start]:
2614
if neighbor not in visited:
27-
sort = topological_sort(neighbor, visited, sort)
28-
# if all neighbors visited add current to sort
15+
topological_sort(neighbor, visited, sort)
2916
sort.append(current)
30-
# if all vertices haven't been visited select a new one to visit
31-
if len(visited) != len(vertices):
32-
for vertice in vertices:
33-
if vertice not in visited:
34-
sort = topological_sort(vertice, visited, sort)
35-
# return sort
3617
return sort
3718

38-
3919
if __name__ == "__main__":
4020
sort = topological_sort("a", [], [])
21+
sort.reverse() #Top down approach
4122
print(sort)

0 commit comments

Comments
 (0)
Please sign in to comment.