美文网首页
图论-拓扑排序

图论-拓扑排序

作者: 酱油和醋 | 来源:发表于2024-03-09 22:43 被阅读0次

    最近又写到有向图的拓扑排序,这段排序代码在几年前也写过。做个简单记录,本次用到了google guava的Graph类。
    主要是用方法可以参考:https://www.jianshu.com/p/78786a4f2cf1

    相关排序可以参考: https://juejin.cn/post/7251844608774209592

    图1

    拓扑排序:
    Visited node: A
    Visited node: D
    Visited node: E
    Visited node: B
    Visited node: C
    Visited node: F

    但在实际的工作中,并不是单纯的对节点进行排序或者遍历,比如说常用的就是A有三条下游节点时,则选择其中一条路径执行,其余路径均不可执行。


    图2

    在拓扑排序的基础上,我们增加不执行节点的判断与处理。具体处理逻辑如下:

    public class UnReachableTopologyTraversal {
    
    
        public static void topologyTraverse(MutableGraph<String> graph, Function<String, Boolean> function) {
            // 1.1 拓扑排序需要的辅助队列。
            Queue<String> queue = Queues.newLinkedBlockingQueue();
            //1.2 初始化本次不执行节点集合
            List<String> unReachNodeList = Lists.newArrayList();
    
    
            // 2. 将root节点(入度为0的节点)入队列。
            for (String node : graph.nodes()) {
                if (graph.inDegree(node) == 0) {
                    queue.add(node);
                }
            }
    
    
            // 3. 非root节点(入度非0的节点)对应的入度记录表。
            Map<String, Integer> nodeIdInDegreeMap = graph.nodes().stream()
                    .filter(task -> graph.inDegree(task) != 0)
                    .collect(Collectors.toMap(node -> node, node -> graph.inDegree(node)));
    
    
            // 4. 拓扑遍历
            while (!queue.isEmpty()) {
                //5. 随机选取其中一个可执行节点
                List<String> allNodes = new ArrayList<>(queue);
                Collections.shuffle(allNodes);
                queue = new LinkedList<>(allNodes);
                String current = queue.poll();
    
    
    
    
                // 6. 判断是不是不可执行节点,如果是不可执行节点,则跳过
                if (unReachNodeList.contains(current)) {
                    continue;
                }
    
    
                //7.1 执行本次节点函数
                function.apply(current);
    
    
                //7.2 后续节点入度减一
                subSuccessorInDegree(current, graph, nodeIdInDegreeMap);
    
    
                //8.1 标记不可执行节点
                for (String node : allNodes) {
                    if (!unReachNodeList.contains(node) && !StringUtils.equals(node,
                            current)) {
                        unReachNodeList.add(node);
                        subSuccessorInDegree(node, graph, nodeIdInDegreeMap);
                        markSuccessorUnReachable(graph, node, unReachNodeList, nodeIdInDegreeMap);
                    }
                }
    
    
                //9. 拓扑排序, 将当前节点的后继节点入度减一, 如果入度为0, 则加入队列, 等待调度。
                for (String node : graph.successors(current)) {
                    if (nodeIdInDegreeMap.get(node) == 0) {
                        queue.add(node);
                    }
                }
            }
        }
    
    
        /**
         * 将当前节点的后续节点入度-1
         * @param currentNode
         * @param graph
         * @param nodeIdInDegreeMap
         */
        private static void subSuccessorInDegree(String currentNode,
                                                 Graph<String> graph, Map<String, Integer> nodeIdInDegreeMap) {
    
    
            Set<String> successorNodes = graph.successors(currentNode);
            if (successorNodes == null || successorNodes.size() == 0) {
                return;
            }
    
    
            for (String successor : successorNodes) {
                Integer inDegree = nodeIdInDegreeMap.get(successor);
                nodeIdInDegreeMap.put(successor, inDegree - 1);
            }
        }
    
    
    
    
        /**
         * 标记当前节点的后续节点为不可执行节点
         * @param graph
         * @param currentNode
         * @param unReachNodeList
         * @param nodeIdInDegreeMap
         */
        private static void markSuccessorUnReachable(Graph<String> graph, String currentNode,
                                                     List<String> unReachNodeList, Map<String, Integer> nodeIdInDegreeMap) {
            Set<String> afterNodeList = graph.successors(currentNode);
            for (String afterNode : afterNodeList) {
                boolean unReachable = true;
                
                //当前节点的前置节点如果存在不可执行节点,则不需要递归不可执行
                Set<String> preAfterNodeList = graph.predecessors(afterNode);
                for (String preAfterNode : preAfterNodeList) {
                    if (!unReachNodeList.contains(preAfterNode)) {
                        unReachable = false;
                    }
                }
                
                //后续节点为不可执行节点,继续递归不可执行
                if (unReachable) {
                    unReachNodeList.add(afterNode);
                    subSuccessorInDegree(afterNode, graph, nodeIdInDegreeMap);
                    markSuccessorUnReachable(graph, afterNode, unReachNodeList, nodeIdInDegreeMap);
                }
            }
        }
    
    
    
    
        public static void main(String[] args) {
            MutableGraph<String> graph = GraphBuilder.directed() //指定为有向图
                    .nodeOrder(ElementOrder.<String>insertion()) //节点按插入顺序输出
                    //(还可以取值无序unordered()、节点类型的自然顺序natural())
                    .expectedNodeCount(6) //预期节点数
                    .allowsSelfLoops(false) //不允许自环
                    .build();
    
    
            graph.putEdge("A", "B");
            graph.putEdge("A", "D");
            graph.putEdge("A", "E");
            graph.putEdge("B", "C");
            graph.putEdge("C", "F");
            graph.putEdge("D", "F");
    
    
            graph.addNode("A");
            graph.addNode("B");
            graph.addNode("C");
            graph.addNode("D");
            graph.addNode("E");
    
    
            System.out.println("选择分支执行:");
            UnReachableTopologyTraversal.topologyTraverse(graph, node -> {
                System.out.println("Visited node: " + node);
            });
    
    
        }
    }
    
    结果1
    结果2
    结果3

    相关文章

      网友评论

          本文标题:图论-拓扑排序

          本文链接:https://www.haomeiwen.com/subject/klbuzdtx.html