void topSortDFS(DirectedGraphNode* node, unordered_map<DirectedGraphNode*, vector<DirectedGraphNode*>>& parents, unordered_set<DirectedGraphNode*>& visited, vector<DirectedGraphNode*>& result) { if (visited.insert(node).second) { for (DirectedGraphNode* parent : parents[node]) { topSortDFS(parent, parents, visited, result); } result.push_back(node); } }
void topSortDFS( DirectedGraphNode *node, unordered_map<DirectedGraphNode *, vector<DirectedGraphNode *>> &ancestors, unordered_set<DirectedGraphNode *> &scheduled, vector<DirectedGraphNode *> &output) { if (scheduled.insert(node).second) { for (auto& ancestor: ancestors[node]) { topSortDFS(ancestor, ancestors, scheduled, output); } output.emplace_back(node); } }
vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) { vector<DirectedGraphNode*>result; unordered_set<DirectedGraphNode*> visited; unordered_map<DirectedGraphNode*, vector<DirectedGraphNode*>> parents; for (DirectedGraphNode* node : graph) { findParents(node, visited, parents); } visited.clear(); for (DirectedGraphNode* node : graph) { topSortDFS(node, parents, visited, result); } return result; }
// @param graph: A list of Directed graph node // @return: Any topological order for the given graph. // vector<DirectedGraphNode *> topSort(vector<DirectedGraphNode*> graph) { vector<DirectedGraphNode *> output; // Find ancestors of each node by DFS unordered_set<DirectedGraphNode *> nodes; unordered_map<DirectedGraphNode *, vector<DirectedGraphNode *>> ancestors; for (auto& node :graph) { findDependencyDFS(node, nodes, ancestors); } // Output topological order by DFS unordered_set<DirectedGraphNode *> scheduled; for (auto& node : graph) { topSortDFS(node, ancestors, scheduled, output); } return output; }