Problem

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example

Given n = 2, prerequisites = [[1,0]]
Return true

Given n = 2, prerequisites = [[1,0],[0,1]]
Return false

Solution

class Solution {
    public boolean canFinish(int num, int[][] pre) {
        //initialize graph: create list for each node(int)
        if (pre.length > num*(num-1)/2) return false;
        List[] graph = new ArrayList[num];
        for (int i = 0; i < num; i++) graph[i] = new ArrayList<>();
        
        //build graph: save children nodes to the corresponding list
        //save indegrees of children nodes to indegree[] array
        int[] indegree = new int[num];
        for (int i = 0; i < pre.length; i++) {
            indegree[pre[i][0]]++;
            graph[pre[i][1]].add(pre[i][0]);
        }
        
        //create queue to do BFS
        //save parent nodes which don't have pre courses (indegree == 0) to the queue
        Deque<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < num; i++) {
            if (indegree[i] == 0) queue.offer(i);
        }
        
        //BFS: poll the parent nodes, if they have children, offer to the queue
        int count = 0;
        while (!queue.isEmpty()) {
            Integer root = queue.poll();
            count++;
            List<Integer> children = graph[root];
            for (int child: children) {
                if (indegree[child] == 1) {
                    queue.offer(child);
                }
                indegree[child]--;
            }
        }
        
        return count == num;
    }
}

linspiration
161 声望53 粉丝