0
点赞
收藏
分享

微信扫一扫

图-拓扑排序算法

乱世小白 2022-02-17 阅读 86
算法图论

1、算法实现思路

1.1、思路:

 

 

 

 

1.2、代码:

//图
public class Graph {
    //点集合,代表编号为N的节点是啥
    public HashMap<Integer, Node> nodes;
    //边集合
    public HashSet<Edge> edges;

    public Graph() {
        nodes = new HashMap<>();
        edges = new HashSet<>();
    }
}
// directed graph and no loop
public static List<Node> sortedTopology(Graph graph) {
    // key:某一个node
    // value:剩余的入度
    HashMap<Node, Integer> inMap = new HashMap<>();
    // 入度为0的点,才能进这个队列
    Queue<Node> zeroInQueue = new LinkedList<>();
    for (Node node : graph.nodes.values()) {
        //保存每个节点以及该节点的入度
        inMap.put(node, node.in);
        if (node.in == 0) {
            zeroInQueue.add(node);
        }
    }
    // 拓扑排序的结果,依次加入result
    List<Node> result = new ArrayList<>();
    while (!zeroInQueue.isEmpty()) {
        Node cur = zeroInQueue.poll();
        result.add(cur);
        for (Node next : cur.nexts) {
            //当前节点的邻居入度减去1
            inMap.put(next, inMap.get(next) - 1);
            if (inMap.get(next) == 0) {
                zeroInQueue.add(next);
            }
        }
    }
    return result;
}
举报

相关推荐

0 条评论