课程表排序问题,图的拓扑排序!

导读:本篇文章讲解 课程表排序问题,图的拓扑排序!,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

题目描述:

课程表排序问题,图的拓扑排序!

 题解:

class Solution {
    //本题是求图的拓扑排序
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        List<List<Integer>> list=new ArrayList<>();//用于构造邻接表
        int[] count=new int[numCourses];//用于统计每个顶点的入度数
        //初始化邻接表
        for(int i=0;i<numCourses;i++){
            list.add(new ArrayList<Integer>());
        }
        //开始构造邻接表和统计入度数
        for(int[] pre:prerequisites){
            list.get(pre[1]).add(pre[0]);//完成pre[0]前先完成pre[1]
            count[pre[0]]++;//pre[0]的入度+1;
        }
        Queue<Integer> queue=new LinkedList<Integer>();
        //将度为0的顶点入列
        for(int i=0;i<numCourses;i++){
            if(count[i]==0){
                queue.offer(i);
            }
        }
        int[] res=new int[numCourses];//存放学完的课程
        int index=0;
        while(!queue.isEmpty()){
            int v=queue.poll();//顶点出列
            res[index++]=v;
            for(int u:list.get(v)){//v顶点可以到达的其它顶点
                count[u]--;
                if(count[u]==0){
                    queue.offer(u);
               }
            }
        }
        return index==numCourses?res:new int[0];
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/116058.html

(0)
Java光头强的头像Java光头强

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!