Lintcode 拓扑排序

题目网址: 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;
     }
 };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值