Generation

generate functionThu, 01 Dec 2022

Return a topologically sorted list of nodes from a graph represented by an adjacency array dictionary

def topologicalSort(graph): visited = [] stack = [] for v in graph: if v not in visited: topologicalSortUtil(v, graph, visited, stack) return stack def topologicalSortUtil(curr, graph, visited, stack): visited.append(curr) for v in graph[curr]: if v not in visited: topologicalSortUtil(v, graph, visited, stack) stack.insert(0, curr) graph = { 'a': ['b', 'c', 'd'], 'b': ['e'], 'c': ['e'], 'd': ['e'], 'e': [] } print(topologicalSort(graph))

Questions about programming?Chat with your personal AI assistant