/**
* Definition for Directed graph.
* struct DirectedGraphNode
* {
* int label;
* vector<DirectedGraphNode *> neighbors;
* DirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution
{
public:
/*
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*>& graph)
{
vector<DirectedGraphNode*> result;
unordered_map<DirectedGraphNode*, int> node_indegrees;
for (auto node : graph)
{
vector<DirectedGraphNode*> neighbors = node->neighbors;
for (auto neighbor : neighbors)
{
node_indegrees[neighbor]++;
}
}
queue<DirectedGraphNode*> nodes;
for (auto node : graph)
{
if (node_indegrees[node] == 0)
{
nodes.push(node);
result.push_back(node);
}
}
while (!nodes.empty())
{
DirectedGraphNode* node = nodes.front();
nodes.pop();
for (auto neighbor : node->neighbors)
{
node_indegrees[neighbor]--;
if (node_indegrees[neighbor] == 0)
{
nodes.push(neighbor);
result.push_back(neighbor);
}
}
}
return result;
}
};