import LinkedList from '../../data-structures/sequences/linked-list' import { GraphNode } from '../graphs/graph-node' /** * Perform a topological sort through a directed graph using the depth first technique. * * Time complexity: O(V+E) * Space complexity: O(V) (recursion and output) * * @param startNode - The node to begin the search at * @return {Array>} */ export const topologicalSortDepthFirst = ( graph: Map, Array>> ): Array => { const output = new LinkedList() const visited = new Set>() // for every node in the graph, perform a dfs, where the dfs adds the nodes to the output in the correct order for (const node of graph.keys()) { if (!visited.has(node)) dfs(node, graph, visited, output) } return Array.from(output) } const dfs = ( root: GraphNode, graph: Map, Array>>, visited: Set>, output: LinkedList ): void => { visited.add(root) const children = graph.get(root) if (children) { for (const child of children) { dfs(child, graph, visited, output) } } output.addFront(root.val) }