Skip to content

Instantly share code, notes, and snippets.

@timshen91
Last active July 20, 2018 22:19
Show Gist options
  • Save timshen91/e71f8ed0794f70863d4b to your computer and use it in GitHub Desktop.
Save timshen91/e71f8ed0794f70863d4b to your computer and use it in GitHub Desktop.
Kahn's algorithm for topological sort
template<typename NodeRef>
class Graph {
public:
std::vector<NodeRef> allNodes() const;
std::vector<NodeRef> getChildren(NodeRef) const;
};
template<typename NodeRef>
std::vector<NodeRef> TopologicalSort(const Graph<NodeRef>& G) {
std::map<NodeRef, unsigned> RefCount;
for (NodeRef From : G.allNodes()) {
RefCount.emplace(From, 0);
for (NodeRef To : G.getChildren(From)) {
RefCount[To]++;
}
}
std::queue<NodeRef> Q;
for (auto& Entry : RefCount) {
if (Entry.second == 0) {
Q.push(Entry.first);
}
}
std::vector<NodeRef> Results;
while (!Q.empty()) {
NodeRef From = Q.front();
Q.pop();
Results.push_back(From);
for (NodeRef To : G.getChildren(From)) {
if (--RefCount[To] == 0) {
Q.push(To);
}
}
}
return Results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment