Java流程图式结构数据拓扑排序排序

import java.util.*;

public class TopologicalSort {
    public static void main(String[] args) {
      //当前节点:下一节点关联数据
        Map<Integer, List<Integer>> graph = new HashMap<>();
        graph.put(1, Arrays.asList(2, 3));
        graph.put(2, Arrays.asList(4, 5));
        graph.put(3, Arrays.asList(4, 6));
        graph.put(4, Collections.singletonList(7));
        graph.put(5, Collections.singletonList(7));
        graph.put(6, Collections.singletonList(7));
        graph.put(7, Collections.emptyList());

        List<Integer> sortedList = topologicalSort(graph);
        System.out.println("拓扑排序结果:" + sortedList);
    }

    public static List<Integer> topologicalSort(Map<Integer, List<Integer>> graph) {
        // 统计每个节点的入度
        Map<Integer, Integer> inDegreeMap = new HashMap<>();
        //默认每个节点为0
        for (Integer node : graph.keySet()) {
            inDegreeMap.put(node, 0);
        }
        //统计右节点被多少左节点关联过,起始节点因为没有被关联过所以为0
        for (List<Integer> neighbors : graph.values()) {
            for (Integer neighbor : neighbors) {
                inDegreeMap.put(neighbor, inDegreeMap.getOrDefault(neighbor, 0) + 1);
            }
        }

        List<Integer> sortedList = new ArrayList<>();

        // 将入度为0(起始)的节点加入队列
        Queue<Integer> queue = new LinkedList<>();
        for (Integer node : inDegreeMap.keySet()) {
            if (inDegreeMap.get(node) == 0) {
                queue.offer(node);
            }
        }

        // 使用BFS进行拓扑排序
        while (!queue.isEmpty()) {
            Integer node = queue.poll();
            sortedList.add(node);
          //获取下一节点
            List<Integer> neighbors = graph.get(node);
            for (Integer neighbor : neighbors) {
                // 更新其相邻节点的入度,如果下一节点被多个前节点关联,入度数不为1,则不加入队列,入度依次递减
                inDegreeMap.put(neighbor, inDegreeMap.get(neighbor) - 1);
                // 如果更新后的入度为0,则加入队列,直到被最后一个相同关联的前节点消费,防止多次消费
                if (inDegreeMap.get(neighbor) == 0) {
                    queue.offer(neighbor);
                }
            }
        }

        return sortedList;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值