题目网址: http://www.lintcode.com/zh-cn/problem/topological-sorting/#
拓扑排序是一种检测图中是否有环的算法
/**
* 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) {
// write your code here
vector<DirectedGraphNode*> res;
if(graph.empty())
return res;
map<DirectedGraphNode*, int> indegree;
queue<DirectedGraphNode*> q;
//找出所有节点的入度
for(auto i : graph)
{
for(auto j : i->neighbors)
++indegree[j];
}
//找出入度为0的点
for(auto i : graph)
{
if(indegree[i] == 0)
{
q.push(i);
}
}
//BFS:将当前入度为0的节点出队列,再将当前节点邻接表中入度为0的节点(未入过队列的)入队,循环
while(!q.empty())
{
DirectedGraphNode* cur_node = q.front();
q.pop();
res.push_back(cur_node);
for(auto i : cur_node->neighbors)
{
if(--indegree[i] == 0)
q.push(i);
}
}
return res;
}
};