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.
Note
You can assume that there is at least one topological order in the graph.

Example
For graph as follow: 



The topological order can be:

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

or

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

or

....



Challenge
Can you do it in both BFS and DFS?


public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        // write your code here
        if (graph == null || graph.size() == 0) {
            return graph;
        }
        HashMap<DirectedGraphNode,Integer>map= new HashMap<DirectedGraphNode,
                                                    Integer>();
        Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();
        ArrayList<DirectedGraphNode> res = new ArrayList<DirectedGraphNode>();
// 对宽度优先搜索加了条件--- 通过map 构造关系函数
        for (DirectedGraphNode node : graph) {
            for (DirectedGraphNode i : node.neighbors) {
                
                 map.put(i, map.getOrDefault(i, 0) + 1);
                
            }
        }
        for (DirectedGraphNode i : graph) {
            if (!map.containsKey(i)) {
                 queue.offer(i);
                
            }
        }
        
        while (!queue.isEmpty()) {
            DirectedGraphNode node = queue.poll();
            res.add(node);
            for (DirectedGraphNode i : node.neighbors) {
                 map.put(i, map.get(i) - 1);
                 if (map.get(i) == 0) {
                     queue.offer(i);
                 }
             }
        }
        return res;
}

容器此处还可以用 hashMap, 其中set既可以表示里面的边又可以表示入度数, 但是此处只需要知道入度数就可以了. 

之前还有用 int [] ArrayList[] 来表示的同set, 因为坐标可以表示map中的键, 容器内元素可以表示值.

 HashMap<DirectedGraphNode, Set<DirectedGraphNode>> map = new HashMap<DirectedGraphNode, Set<DirectedGraphNode>>();
         for (DirectedGraphNode each : graph) {
            map.put(each, new HashSet<DirectedGraphNode>());
        }
       for (DirectedGraphNode each : graph) {
           for (int i=0; i<each.neighbors.size(); i++) {
                 map.get(each.neighbors.get(i)).add(each);
             }
}
原文地址:https://www.cnblogs.com/apanda009/p/7226234.html