lintcode-medium-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.

 

Example

For graph as follow:

picture

The topological order can be:

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

Can you do it in both BFS and DFS?

 

/**
 * 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 graph;
        
        ArrayList<DirectedGraphNode> res = new ArrayList<DirectedGraphNode>();
        HashMap<DirectedGraphNode, Integer> map = new HashMap<DirectedGraphNode, Integer>();
        
        for(DirectedGraphNode node: graph)
            map.put(node, 0);
        
        for(DirectedGraphNode node: graph){
            for(DirectedGraphNode n: node.neighbors){
                    map.put(n, map.get(n) + 1);
            }
        }
        
        DirectedGraphNode start = null;
        Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();
        
        for(DirectedGraphNode temp: graph){
            if(map.get(temp) == 0){
                start = temp;
                queue.offer(start);
                res.add(start);
            }
        }
        
        while(!queue.isEmpty()){
            DirectedGraphNode temp = queue.poll();
            
            for(DirectedGraphNode n: temp.neighbors){
                map.put(n, map.get(n) - 1);
                
                if(map.get(n) == 0){
                    queue.offer(n);
                    res.add(n);
                }
            }
        }
        
        return res;
    }
}

 

posted @ 2016-04-07 11:57  哥布林工程师  阅读(141)  评论(0编辑  收藏  举报