拓扑排序

给定一个有向图,图节点的拓扑排序被定义为:

对于每条有向边A–> B,则A必须排在B之前  
拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点  
找到给定图的任一拓扑排序

/** * 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) {
        // 统计节点入度 >0的点
        ArrayList<DirectedGraphNode> result = new ArrayList<>();
        Map<DirectedGraphNode, Integer> map = new HashMap<>();
        for (DirectedGraphNode node : graph) {
            for (DirectedGraphNode neighbor : node.neighbors) {
                if (map.containsKey(neighbor)) {
                    map.put(neighbor, map.get(neighbor) + 1);
                } else {
                    map.put(neighbor, 1);
                }
            }
        }
        //找出入度为0的点,即不在上述集合中的点
        Queue<DirectedGraphNode> queue = new LinkedList<>();
        for (DirectedGraphNode n : graph) {
            if (!map.containsKey(n)) {
                queue.offer(n);
                result.add(n);
            }
        }
        //bfs,不断找出入度降为0的点
        while (!queue.isEmpty()) {
            DirectedGraphNode node = queue.poll();
            for (DirectedGraphNode neighbor : node.neighbors) {
                map.put(neighbor, map.get(neighbor) - 1);
                if (map.get(neighbor) == 0) {
                    queue.offer(neighbor);
                    result.add(neighbor);
                }
            }
        }
        return result;
    }
}
点赞