mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-21 08:42:03 +00:00
Merge 7a2ee6eba2
into 6c92c5a539
This commit is contained in:
commit
c64f8c6cbd
|
@ -15,27 +15,27 @@ edges: dict[str, list[str]] = {
|
||||||
vertices: list[str] = ["a", "b", "c", "d", "e"]
|
vertices: list[str] = ["a", "b", "c", "d", "e"]
|
||||||
|
|
||||||
|
|
||||||
def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
|
class Topo:
|
||||||
"""Perform topological sort on a directed acyclic graph."""
|
def topo_sort(self):
|
||||||
current = start
|
visited = set()
|
||||||
# add current to visited
|
stack = []
|
||||||
visited.append(current)
|
|
||||||
neighbors = edges[current]
|
def dfs(node):
|
||||||
for neighbor in neighbors:
|
visited.add(node)
|
||||||
# if neighbor not in visited, visit
|
|
||||||
if neighbor not in visited:
|
for neighbor in edges[node]:
|
||||||
sort = topological_sort(neighbor, visited, sort)
|
if neighbor not in visited:
|
||||||
# if all neighbors visited add current to sort
|
dfs(neighbor)
|
||||||
sort.append(current)
|
|
||||||
# if all vertices haven't been visited select a new one to visit
|
stack.append(node)
|
||||||
if len(visited) != len(vertices):
|
|
||||||
for vertice in vertices:
|
return stack
|
||||||
if vertice not in visited:
|
|
||||||
sort = topological_sort(vertice, visited, sort)
|
result = dfs("a")
|
||||||
# return sort
|
return result[::-1]
|
||||||
return sort
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
sort = topological_sort("a", [], [])
|
topo = Topo()
|
||||||
|
sort = topo.topo_sort()
|
||||||
print(sort)
|
print(sort)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user