Lintcode. Topological Sort

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 be 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. You can assume that there is at least one topological order in the graph and graph is of DAG type (directed acyclic graph).

Example

For given graph

dag

The topological order can be:

1, 3, 0, 2, 5
3, 1, 2, 5, 0

Topological sort is commonly used for dependencies resolution in processes like instruction scheduling or defining build order of compilation units. For more information, please watch Topological Sort by Prof. Sedgewick

Java (reverse DFS)
Time complexity: O(V + E), V – num of vertexes, E – num of edges
Space complexity: O(V) + O(E) (for recursive call stack), V – num of vertexes, E – num of edges

/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     ArrayList<DirectedGraphNode> neighbors;
 *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 * };
 */
public class Solution {
    /**
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */    
    public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        // write your code here
        if (graph == null || graph.isEmpty()){
            return new ArrayList<>();
        }
        
        Stack<DirectedGraphNode> stack = new Stack<>();
        Set<Integer> seen = new HashSet<>();
        
        for (DirectedGraphNode node : graph){
            reverseDFS(node, seen, stack);     
        }
        
        Collections.reverse(stack);
        
        return new ArrayList<>(stack);
        
    }
    
    private void reverseDFS(DirectedGraphNode node, Set<Integer> seen, Stack<DirectedGraphNode> stack){
        if (seen.contains(node.label)){
            return;
        }
        
        for (DirectedGraphNode neighbour : node.neighbors){
            if (!seen.contains(neighbour.label)){
                reverseDFS(neighbour, seen, stack);    
            }
        }
        
        stack.push(node);
        seen.add(node.label);
    }
}

Java (BFS)
Time complexity: O(V*D)(to init degree map) + O(V + E), V – num of vertexes, D – max vertex degree, E – num of edges
Space complexity: O(V), V – num of vertexes

/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     ArrayList<DirectedGraphNode> neighbors;
 *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 * };
 */
public class Solution {
    /**
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */    
    public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        // write your code here
        if (graph == null || graph.size() == 0){
            return new ArrayList<>();
        }
        
        Map<DirectedGraphNode, Integer> inDegreeMap = getInDegreeMap(graph);
        Queue<DirectedGraphNode> q = new LinkedList<>();
        
        for (DirectedGraphNode node : graph){
            if (!inDegreeMap.containsKey(node)){
                q.offer(node);
            }
        }
        
        if (q.isEmpty()){//graph has cycles, not possible to build topSort
            return new ArrayList<>();    
        }
        
        ArrayList<DirectedGraphNode> res = new ArrayList<>();
        
        while (!q.isEmpty()){
            DirectedGraphNode curr = q.poll();
            res.add(curr);
            for (DirectedGraphNode neighb : curr.neighbors){
                int inDegree = inDegreeMap.get(neighb);
                inDegreeMap.put(neighb, inDegree - 1);
                if (inDegree - 1 == 0){
                    q.offer(neighb);
                }
            }
        }
        
        return res;
        
        
    }
    
    private Map<DirectedGraphNode, Integer> getInDegreeMap(List<DirectedGraphNode> graph){
        Map<DirectedGraphNode, Integer> inDegreeMap = new HashMap<>();  
        for (DirectedGraphNode node : graph){
            for (DirectedGraphNode neighb : node.neighbors){
                if (!inDegreeMap.containsKey(neighb)){
                    inDegreeMap.put(neighb, 1);
                } else {
                    inDegreeMap.put(neighb, inDegreeMap.get(neighb) + 1);
                }
            }
        }
        
        return inDegreeMap;
    }
    
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s