Last active
July 20, 2018 22:19
-
-
Save timshen91/e71f8ed0794f70863d4b to your computer and use it in GitHub Desktop.
Kahn's algorithm for topological sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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