[lintcode] Topological Sorting


Topological Sorting

Medium Topological Sorting

25%

Accepted

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.

Have you met this question in a real interview?

Yes
Example

For graph as follow:

picture

The topological order can be:

[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
Note

You can assume that there is at least one topological order in the graph.

Challenge

Can you do it in both BFS and DFS?

 

/**
 * 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*> ans;
        queue<DirectedGraphNode*> q;
        unordered_map<DirectedGraphNode*, int> inDegree;
        for(auto it = graph.begin(); it!= graph.end(); it++){
            if(inDegree.find(*it) == inDegree.end()){
                inDegree[*it] = 0;
            }
            for(auto neighbor = (*it)->neighbors.begin(); neighbor != (*it)->neighbors.end(); neighbor++){
                if(inDegree.find(*neighbor) == inDegree.end()){
                    inDegree[*neighbor] = 1;
                }else{
                    inDegree[*neighbor]++;
                }
            }
        }
        for(auto it = inDegree.begin(); it != inDegree.end(); it++){
            if(it->second == 0){
                q.push(it->first);
            }
        }
        while(!q.empty()){
            DirectedGraphNode * node = q.front();
            q.pop();
            ans.push_back(node);
            for(auto neighbor = node->neighbors.begin(); neighbor != node->neighbors.end(); neighbor++){
                inDegree[*neighbor]--;
                if(inDegree[*neighbor] == 0){
                    q.push(*neighbor);
                }
            }
        }
        return ans;
    }
};

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.