zoukankan      html  css  js  c++  java
  • 拓扑排序

    /**
     * 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
            ArrayList<DirectedGraphNode> order = new ArrayList<>();
            if (graph == null) {
                return order;
            }
            //1.count indegree
            Map<DirectedGraphNode, Integer> indegree = getIndegree(graph);
            //2.bfs
            Queue<DirectedGraphNode> queue = new LinkedList<>();
            for (DirectedGraphNode node : graph) {
                if (indegree.get(node) == 0) {
                    queue.offer(node);
                    order.add(node);
                }
            }
            while (!queue.isEmpty()) {
                DirectedGraphNode node = queue.poll();
                for (DirectedGraphNode neighbor : node.neighbors) {
                    //node -> neighbor 
                    indegree.put(neighbor, indegree.get(neighbor) - 1);
                    if (indegree.get(neighbor) == 0) {
                        queue.offer(neighbor);
                        order.add(neighbor);
                    }
                }
            }
            //check 环状依赖
            if (order.size() == graph.size()) {
                return order;
            } else {
                return null;
            }
    
        }
        private Map<DirectedGraphNode, Integer> getIndegree(ArrayList<DirectedGraphNode> graph) {
            //1.统计indegree,用map装
            Map<DirectedGraphNode, Integer> indegree = new HashMap();
            //初始化
            for (DirectedGraphNode node : graph) {
                indegree.put(node, 0);
            }
            for (DirectedGraphNode node: graph) {
                for (DirectedGraphNode neighbor : node.neighbors) {
                    //node -> neighbor
                    indegree.put(neighbor, indegree.get(neighbor)+1);
                }
            }
            return indegree;
        }
    }
    View Code
  • 相关阅读:
    测试用例模板和编写目的
    使用AndroidStudio配置码云时,提醒following remotes are already on gitee git
    win10操作系统查看电池损耗,电池使用时间
    windows技巧03----win的一些组合键
    windows技巧02---------输入特殊字符
    windows技巧01------------记事本默认保存修改时间
    word2010如何让第一页不显示页码
    docker镜像管理基础
    docker基础用法
    SaltStack进阶
  • 原文地址:https://www.cnblogs.com/yunyouhua/p/6938297.html
Copyright © 2011-2022 走看看