I am trying to self study algorithms and this is my attempt at topological sort using Tarjan's version of DFS. It runs correctly for the graph I included. Can someone tell me if this is correct and if/what optimizations I can make?
graph = {
'A':['C'],
'B': ['C', 'D'],
'C': ['E'],
'D': ['F'],
'E': ['F'],
'F': ['G'],
'G': [],
}
def topological_sort(graph):
visited, stack = set(), []
for vertex in graph:
handle_vertex(graph, vertex, visited, stack)
print(stack)
def handle_vertex(graph, vertex, visited, stack):
if vertex not in visited:
visited.add(vertex)
for neighbors in graph[vertex]:
if neighbors not in visited:
handle_vertex(graph, neighbors, visited, stack)
if vertex not in stack:
stack.insert(0, vertex)
return stack
print(topological_sort(graph))