Leetcode 207. Course Schedule

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?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

思路:
寬度優先搜索,用一個數組存儲每個課程的前置課程數量,用一個二維list存儲每個課程可解鎖的所有課程。
寬搜時,每搜索到一個課程,就把他能解鎖的所有子課程的前置課程數減1,如果某個子課程前置課程數歸0,就把它加入到隊列中。
最后比較寬搜到的課程數是否與課程總數相等。

public boolean canFinish(int numCourses, int[][] prerequisites) {
    //tip 后面的是前置條件

    int[] preCount = new int[numCourses];
    List<List<Integer>> unlock = new ArrayList<>();
    for (int i = 0; i < numCourses; i++) {
        unlock.add(new ArrayList<>());
    }

    for (int i = 0; i < prerequisites.length; i++) {
        int[] pre = prerequisites[i];
        preCount[pre[0]] += 1;
        unlock.get(pre[1]).add(pre[0]);
    }

    //use queue to search and count
    int cnt = 0;
    Queue<Integer> q = new LinkedList<>();
    for (int i = 0; i < numCourses; i++) {
        if (preCount[i] == 0) {
            q.offer(i);
        }
    }
    while (!q.isEmpty()) {
        int num = q.poll();
        cnt++;
        List<Integer> subs = unlock.get(num);
        for (int i = 0; i < subs.size(); i++) {
            int next = subs.get(i);
            preCount[next] -= 1;
            if (preCount[next] == 0) {
                q.offer(next);
            }
        }
    }

    return cnt == numCourses;
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容