Skip to content

Commit 76db9e0

Browse files
Fixes 12192
1 parent e321b1e commit 76db9e0

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

sorts/topological_sort.py

+33-4
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,51 @@
1+
"""Topological Sort on Directed Acyclic Graph(DAG)"""
2+
3+
# a
4+
# / \
5+
# b c
6+
# / \
7+
# d e
8+
19
edges: dict[str, list[str]] = {
210
"a": ["c", "b"],
311
"b": ["d", "e"],
412
"c": [],
513
"d": [],
614
"e": [],
715
}
16+
817
vertices: list[str] = ["a", "b", "c", "d", "e"]
918

19+
# Perform topological sort on a DAG starting from the specified node
1020
def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
11-
visited.append(start)
1221
current = start
13-
for neighbor in edges[start]:
22+
# Mark the current node as visited
23+
visited.append(current)
24+
# List of all neighbors of current node
25+
neighbors = edges[current]
26+
27+
# Traverse all neighbors of the current node
28+
for neighbor in neighbors:
29+
# Recursively visit each unvisited neighbor
1430
if neighbor not in visited:
15-
topological_sort(neighbor, visited, sort)
31+
sort = topological_sort(neighbor, visited, sort)
32+
33+
# After visiting all neighbors, add the current node to the sorted list
1634
sort.append(current)
35+
36+
# If there are some nodes that were not visited (disconnected components)
37+
if len(visited) != len(vertices):
38+
for vertex in vertices:
39+
if vertex not in visited:
40+
sort = topological_sort(vertex, visited, sort)
41+
42+
# Return sorted list
1743
return sort
1844

1945
if __name__ == "__main__":
46+
# Topological Sorting from node "a" (Returns the order in bottom up approach)
2047
sort = topological_sort("a", [], [])
21-
sort.reverse() #Top down approach
48+
49+
# Reversing the list to get the correct topological order (Top down approach)
50+
sort.reverse()
2251
print(sort)

0 commit comments

Comments
 (0)