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.

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

/**
 * 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){
        ArrayList<DirectedGraphNode> res = new ArrayList<>();
        if (graph == null || graph.size() == 0){
            return res;
        }
       
        //计算所有节点的入度,存到HashMap indegree里面 
        Map<DirectedGraphNode,Integer> indegree = new HashMap<>();
        for (DirectedGraphNode node : graph){
            for (DirectedGraphNode neighbor : node.neighbors){
                if (indegree.containsKey(neighbor)){
                    indegree.put(neighbor, indegree.get(neighbor) + 1); 
                } else {
                    indegree.put(neighbor, 1);
                }
            }
        }

        //找到所有入度为零的点,它们都可以作为BFS的起点       
        ArrayList<DirectedGraphNode> startNodes = new ArrayList<>();
        for (DirectedGraphNode node : graph){
            if (!indegree.containsKey(node)){
                startNodes.add(node);
            }
        }
 
        //用Queue数据结构来进行BFS,每次poll()出来一个节点,它的邻居的入度都要减一。
        //如果遇到某个邻居入度变为0,要将改邻居节点加入到Queue里面,并且也要加入到res里面。
        //这里不需要记录visited与否,因为某个节点入度变为0的情况只有一次,不会重复加入。
        Queue<DirectedGraphNode> queue = new LinkedList<>();
        for (DirectedGraphNode startNode : startNodes){
            queue.offer(startNode);
            res.add(startNode);
        }
        while (!queue.isEmpty()){
            DirectedGraphNode curt = queue.poll();
            for (DirectedGraphNode neighbor : curt.neighbors){
                indegree.put(neighbor, indegree.get(neighbor) - 1);
                if (indegree.get(neighbor) == 0){
                    queue.offer(neighbor);
                    res.add(neighbor);
                }
            }
        }
        return res;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/1f9ca5f6c82d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞