拓扑排序解决课程表问题

拓扑排序是专门应用于有向图的算法,可用BFS和DFS的写法来实现。这里只用BFS。
需要有个表记录每个节点的后驱节点以及数组来记录每个节点的入度数(前面有几个节点)。
还需要有个队列来保证得到的都是先上的课程。

class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        if(numCourses <= 0)
            return new int[0];

        //记录每个节点的后驱节点们
        HashSet<Integer>[] adj = new HashSet[numCourses];
        for(int i = 0; i < numCourses; i++){
            adj[i] = new HashSet<>();
        }
        //记录每个节点的入度数
        int[] inDegree = new int[numCourses];

        for(int[] p : prerequisites){
            adj[p[1]].add(p[0]);
            inDegree[p[0]]++;
        }

        //队列让入度为0的先出来,就是先上的课
        Queue<Integer> q = new LinkedList<>();
        for(int i = 0; i < numCourses; i++){
            if(inDegree[i] == 0){
                q.offer(i);
            }

        }

        int[] res = new int[numCourses];
        int count = 0;
        while(!q.isEmpty()){
            Integer head = q.poll();
            res[count++] = head;

            for(Integer success : adj[head]){
                inDegree[success] --;
                if(inDegree[success] == 0){
                    q.offer(success);
                }
            }

        }
        if(count == numCourses){
            return res;
        }
        return new int[0];
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务