lintcode-127-拓扑排序

127-拓扑排序

给定一个有向图,图节点的拓扑排序被定义为:
对于每条有向边A--> B,则A必须排在B之前  
拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点  
找到给定图的任一拓扑排序

注意事项

你可以假设图中至少存在一种拓扑排序

说明

Learn more about representation of graphs

样例

对于下列图:
这个图的拓扑排序可能是:
[0, 1, 2, 3, 4, 5]
或者
[0, 2, 3, 1, 5, 4]
或者
....

挑战

能否分别用BFS和DFS完成?

标签

LintCode 版权所有 Geeks for Geeks Topological Sort 深度优先搜索 宽度优先搜索

思路

使用广度优先搜索,首先统计图中所有节点的入度,若入度为0,则此结点无前驱,可以将其输出,之后,将此结点所有后继节点的入度减1

code

/**
 * 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
        int size = graph.size(), i = 0;
        if(size <= 0) {
            return vector<DirectedGraphNode*>();
        }

        vector<DirectedGraphNode*> result;
        queue<DirectedGraphNode*> noPreNode;
        map<DirectedGraphNode*, int> nodeIndegree;

        getIndegree(graph, nodeIndegree);

        for(i=0; i<size; i++) {
            if(nodeIndegree[graph[i]] == 0) {
                noPreNode.push(graph[i]);
            }
        }

        while(!noPreNode.empty()) {
            result.push_back(noPreNode.front());
            for(i=0; i<noPreNode.front()->neighbors.size(); i++) {
                if(--nodeIndegree[noPreNode.front()->neighbors[i]] == 0) {
                    noPreNode.push(noPreNode.front()->neighbors[i]);
                }
            }
            noPreNode.pop();
        }
        return result;
    }

    void getIndegree(vector<DirectedGraphNode*> graph, map<DirectedGraphNode*, int> &nodeIndegree) {
        int size = graph.size();
        for(int i=0; i<size; i++) {
            int size2 = graph[i]->neighbors.size();
            for(int j=0; j<size2; j++) {
                nodeIndegree[graph[i]->neighbors[j]]++;
            }
        }
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7216894.html