您的位置:首页 > 其它

lintcode-拓扑排序-127

2015-09-19 20:51 281 查看
给定一个有向图,图节点的拓扑排序被定义为:

对于每条有向边A--> B,则A必须排在B之前  

拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点  

/**
* Definition for Directed graph.
* struct DirectedGraphNode {
*     int label;
*     vector<DirectedGraphNode *> neighbors;
*     DirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:

vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) {
vector<DirectedGraphNode*> ret;
if(graph.empty())
return ret;

map<DirectedGraphNode*,int> in; //in为入度
stack<DirectedGraphNode*>   s;  //保存入度为零的节点
for(auto e:graph){
for(auto i:e->neighbors)
++in[i];              //记录每个节点的入度
}

for(auto e:graph)
if(0==in[e])
s.push(e);         //入度为零的节点入栈

while(!s.empty()){        //BFS遍历,搜寻入度为零的节点
DirectedGraphNode* cur=s.top();
s.pop();             //当前节点出栈时,它的相邻节点入度都减一
ret.push_back(cur);
for(auto e:cur->neighbors){
if(--in[e]==0)    //减一后为零则入栈
s.push(e);
}
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: