MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / topological_sort

Function topological_sort

sorts/topological_sort.py:18–36  ·  view source on GitHub ↗

Perform topological sort on a directed acyclic graph.

(start: str, visited: list[str], sort: list[str])

Source from the content-addressed store, hash-verified

16
17
18def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
19 """Perform topological sort on a directed acyclic graph."""
20 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
26 if neighbor not in visited:
27 sort = topological_sort(neighbor, visited, sort)
28 # if all neighbors visited add current to sort
29 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
36 return sort
37
38
39if __name__ == "__main__":

Callers 1

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected