Perform topological sort on a directed acyclic graph.
(start: str, visited: list[str], sort: list[str])
| 16 | |
| 17 | |
| 18 | def 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 | |
| 39 | if __name__ == "__main__": |
no test coverage detected