Someone talked about solving it with DFS, here is the sample, I hope it helps as ref
void topoSortDFS(std::string node, std::unordered_map<std::string, std::vector<std::string>>& graph,
std::vector<std::string>& stack_vec, std::unordered_set<std::string>& visited)
{
visited.insert(node);
for(auto& neighbor : graph[node]) {
if(visited.find(neighbor) == visited.end()) {
topoSortDFS(neighbor, graph, stack_vec, visited);
}
}
stack_vec.push_back(node);
}
std::vector<std::string> taskSchedulingDFS(std::unordered_map<std::string, std::vector<std::string>>& graph)
{
std::vector<std::string> sorted_vector;
std::unordered_set<std::string> visited;
for(auto it = graph.begin(); it != graph.end(); ++it) {
if(visited.find(it->first) == visited.end()) {
topoSortDFS(it->first, graph, sorted_vector, visited);
}
}
std::reverse(sorted_vector.begin(), sorted_vector.end());
return sorted_vector;
}