Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #12192 #12293

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 22 additions & 9 deletions sorts/topological_sort.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,54 @@
"""Topological Sort."""
"""Topological Sort on Directed Acyclic Graph(DAG)"""

# a
# / \
# b c
# b c
# / \
# d e
# d e

edges: dict[str, list[str]] = {
"a": ["c", "b"],
"b": ["d", "e"],
"c": [],
"d": [],
"e": [],
}

vertices: list[str] = ["a", "b", "c", "d", "e"]


# Perform topological sort on a DAG starting from the specified node
def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
"""Perform topological sort on a directed acyclic graph."""
current = start
# add current to visited
# Mark the current node as visited
visited.append(current)
# List of all neighbors of current node
neighbors = edges[current]

# Traverse all neighbors of the current node
for neighbor in neighbors:
# if neighbor not in visited, visit
# Recursively visit each unvisited neighbor
if neighbor not in visited:
sort = topological_sort(neighbor, visited, sort)
# if all neighbors visited add current to sort

# After visiting all neigbors, add the current node to the sorted list
sort.append(current)
# if all vertices haven't been visited select a new one to visit

# If there are some nodes that were not visited (disconnected components)
if len(visited) != len(vertices):
for vertice in vertices:
if vertice not in visited:
sort = topological_sort(vertice, visited, sort)
# return sort

# Return sorted list
return sort


if __name__ == "__main__":
# Topological Sorting from node "a" (Returns the order in bottom up approach)
sort = topological_sort("a", [], [])

# Reversing the list to get the correct topological order (Top down approach)
sort.reverse()

print(sort)