拓扑排序的BFS做法

无论是 directed 还是 undirected Graph,其 BFS 的核心都在于 "indegree",处理顺序也是从 indegree 最小的开始。

算法如下:

1) 先用一个 HashMap 统计下所有节点的 indegree; 

(值越高的,在拓扑排序中位置也就越靠后,因为还有 N = current indegree 的 parent node 们没有处理完。)

2) 因此在循环最开始,我们把所有 indegree = 0作为(均不在 hashmap中) (1)BFS 的起点(进queue) (2)加到 list 中。

3) 在 BFS 过程中,我们依次取出队列里 node 的 neighbors,并把他们的 indegree减去1,代表其 parent node 已经被处理完,有效 indegree 减少。

4) 当减去1之后node 的 indegree 已经是 0 (1)BFS 的起点(进queue) (2)加到 list 中

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
        ArrayList<DirectedGraphNode> list = new ArrayList<DirectedGraphNode>();


        // Key : node
        // Value : current in-degree count
        HashMap<DirectedGraphNode, Integer> map = new HashMap<>();
        for(DirectedGraphNode node : graph){
            for(DirectedGraphNode neighbor : node.neighbors){
                if(!map.containsKey(neighbor)){
                    map.put(neighbor, 1);
                } else {
                    map.put(neighbor, map.get(neighbor) + 1);
                }
            }
        }


        // Now we know each node's in-degree (out is trivial)
        Queue<DirectedGraphNode> queue = new LinkedList<>();


        Iterator<DirectedGraphNode> iter = graph.iterator();
        while(iter.hasNext()){
            DirectedGraphNode node = iter.next();
            // get all nodes without indegree
            if(!map.containsKey(node)){
                queue.offer(node);
                list.add(node);
            }
        }


        while(!queue.isEmpty()){
            DirectedGraphNode node = queue.poll();
            for(DirectedGraphNode next : node.neighbors){
                // node "next"'s parent has been processed
                map.put(next, map.get(next) - 1);
                if(map.get(next) == 0){
                    list.add(next);
                    queue.offer(next);
                } 
            }
        }


        return list;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章