LintCode 127. Topological Sorting

有向图的拓扑排序,主要应用是“判断图中是否有环”

  1. 计算每个节点的入度,即有几个点指向它
  2. 将入度为0的点删掉,然后将其相邻的neighbor的入度减一
  3. 不断重复2步骤,如最后剩下点表示有环,如无环则不会剩下点

本题让求任意的拓扑排序,以下解题步骤:

  • 遍历点,用Hashmap记录每个点的入度
  • 将入度为0的所有点加入队列q
  • 不断pop队列构造排序,将相关点入度减一,重复加入当前入度为0的点
  • 直到队列为空截止
/**
 * 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;
        if (graph.empty()) {
            return result;
        }
        
        unordered_map<DirectedGraphNode *, int> in_degree;
        for (DirectedGraphNode * node: graph) {
            for (DirectedGraphNode * neighbor: node->neighbors) {
                if (in_degree.find(neighbor) == in_degree.end()) {
                    in_degree[neighbor] = 1;
                } else {
                    in_degree[neighbor]++;
                }
            }
        }
        
        queue<DirectedGraphNode *> q;
        for (DirectedGraphNode * node: graph) {
            if (in_degree.find(node) == in_degree.end()) {
                q.push(node);
            }
        }
        
        while(!q.empty()) {
            DirectedGraphNode * head = q.front();
            q.pop();
            result.push_back(head);
            for (DirectedGraphNode *neighbor: head->neighbors) {
                in_degree[neighbor]--;
                if (in_degree[neighbor] == 0) {
                    q.push(neighbor);
                }
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值