Lintcode 127. Topological Sorting


Given an directed graph, a topological order of the graph nodes is defined as follow:
For each directed edge  A -> B  in graph, A must before B in the order list.
The first node in the order can be any node in the graph with no nodes direct to it.
Find any topological order for the given graph.
 Notice
You can assume that there is at least one topological order in the graph.
Have you met this question in a real interview?  
Yes
Clarification
Learn more about representation of graphs
Example
For graph as follow:
The topological order can be:
[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...

テーマ構想:
この問題はtopological sortingのアルゴリズムの一つです.私はdfsを使っています.
実現したのはリンクのアルゴリズム--topological sorting
class Solution {
public:
    /*
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */
    vector topSort(vector& graph) {
        // write your code here
        vector res;
        set visited;
    
        if(graph.size()==0)
            return graph;
        
        for(int i=0;ilabel) == visited.end())
                topSort(res, visited, graph[i]);
        }
        
        reverse(res.begin(), res.end());
        return res;
    }
    
private:
    void topSort(vector& res,
            set& visited, DirectedGraphNode* node){
                
        if(visited.find(node->label) != visited.end())
            return;
           
        visited.insert(node->label);
        for(int i=0; i < node->neighbors.size(); i++){
            topSort(res, visited, node->neighbors[i]);
        }
        res.push_back(node);
    }

};

この方法は,0番目のノードが必ず入度がゼロのノードでなければエラーが発生することを保証する必要がある.
第2の方法はmapを用いてすべてのノードの入度ノードを統計し,queueを用いて入度がゼロのノードを保存し,最後にbfsを用いる.
class Solution {
public:
    /**
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */
    vector topSort(vector graph) {
        // write your code here
        int size = graph.size(), i = 0;
        if(size <= 0) {
            return vector();
        }

        vector result;
        queue noPreNode;
        map nodeIndegree;

        getIndegree(graph, nodeIndegree);

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

    void getIndegree(vector &graph, map &nodeIndegree) {
        int size = graph.size();
        for(int i=0; ineighbors.size();
            for(int j=0; jneighbors[j]]++;
            }
        }
    }
};