拓扑排序

本文介绍了一种用于有向无环图(DAG)的拓扑排序算法,该算法通过寻找并移除入度为0的顶点来生成排序序列。适用于需要按依赖关系排序的场景,如任务调度、依赖包安装等。

适用场景

将图里的定点按照相连的性质进行排序
在这里插入图片描述
排序结果应为:1 2 4 3 5

前提

必须是有向无环

思路

不断找一个入度为 0 的点,放入结果集,再删除节点(更新入度表)。

代码

public class TopologicalSort {
    public static List<Integer> sort(boolean[][] adj, int[] indegree){
        List<Integer> ans = new LinkedList<>();
        Queue<Integer> q = new LinkedList<>();
        for (int i = 0; i < indegree.length; i++) {
            if(indegree[i] == 0)
                q.add(i);
        }
        while(!q.isEmpty()){
            //入度为0的点
            Integer poll = q.poll();
            //结果处理
            ans.add(poll);

            for (int i = 0; i < adj[poll].length; i++) {
                 if(adj[poll][i] && --indegree[i] == 0)
                     q.add(i);
            }
        }

        return ans;
    }

    public static void main(String[] args) {
        boolean[][] adj = new boolean[5][5];
        int[] indegree = new int[5];
        adj[0][1] = true; indegree[1]++;
        adj[0][3] = true; indegree[3]++;
        adj[1][2] = true; indegree[2]++;
        adj[1][3] = true; indegree[3]++;
        adj[2][4] = true; indegree[4]++;
        adj[3][2] = true; indegree[2]++;
        adj[3][4] = true; indegree[4]++;
        List<Integer> sort = sort(adj, indegree);
        for (int i = 0; i < sort.size(); i++) {
            if(i == sort.size() - 1)
                System.out.print(sort.get(i) + 1);
            else
                System.out.print(sort.get(i) + 1 + " -> ");
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值