Topological Sorting
07:18
Given an directed graph, a topological order of the graph nodes is defined as follow:
- For each directed edge
A -> B
in graph, A must before B in the order list. - The first node in the order can be any node in the graph with no nodes direct to it.
Find any topological order for the given graph.
Notice
You can assume that there is at least one topological order in the graph.
For graph as follow:
顺便贴一个topology的视频:https://www.youtube.com/watch?v=ddTC4Zovtbc
/**
* Definition for Directed graph.
* struct DirectedGraphNode {
* int label;
* vector<DirectedGraphNode *> neighbors;
* DirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
private:
void topSortHelper(DirectedGraphNode* curNode, stack<DirectedGraphNode*> &auxStack, set<int> &visited)
{
visited.insert(curNode->label);
for (int i=0; i<curNode->neighbors.size(); i++)
{
if (visited.find(curNode->neighbors[i]->label) == visited.end())
{
topSortHelper(curNode->neighbors[i], auxStack, visited);
}
}
auxStack.push(curNode);//当这个节点已经visit 过它所有的子节点的之后,就把它发到stack中,所以stack的最上层肯定是依赖性最小的,食物链最高的节点
}
public:
/**
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) {
// write your code here
set<int> visited;
stack<DirectedGraphNode*> auxStack;
for (int i=0; i<graph.size(); i++)
{
if (visited.find(graph[i]->label) == visited.end())
{
topSortHelper(graph[i], auxStack, visited);
}
}
vector<DirectedGraphNode*> retVtr;
while (auxStack.size() > 0)
{
retVtr.push_back(auxStack.top());
auxStack.pop();
}
return retVtr;
}
};