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.
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.

click to show more hints.
Hints:This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
Topological sort could also be done via BFS.

思路是BFS + Topological sort,跟 Course Schedule ii 很類(lèi)似。用兩個(gè)HashMap表示入度和Graph. 建立queue來(lái)遍歷節(jié)點(diǎn),先把入度為零的點(diǎn)offer到queue里面,再一個(gè)一個(gè)poll出來(lái)遍歷。用courseRemaining來(lái)記錄還需要遍歷的節(jié)點(diǎn)。每次遍歷某個(gè)節(jié)點(diǎn),要使得它的neighbors的入度減一。(就是當(dāng)前節(jié)點(diǎn)指向的點(diǎn),在這里就是以當(dāng)前節(jié)點(diǎn)作為先修課的課程)如果neighbors當(dāng)中有節(jié)點(diǎn)在入度減一后入度為零,要將其加入到queue里面,同時(shí)courseRemaining自減。

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        if (numCourses <= 1){
            return true;
        }
        if (prerequisites.length == 0 || prerequisites[0].length == 0){
            return true;
        }
        Map<Integer, Integer> indegree = new HashMap<>();
        Map<Integer, Set<Integer>> neighbors = new HashMap<>();
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < prerequisites.length; i++){
           
            if (indegree.containsKey(prerequisites[i][0])){
                indegree.put(prerequisites[i][0], indegree.get(prerequisites[i][0]) + 1);
            } else {
                indegree.put(prerequisites[i][0], 1);
            }
        }
        int coursesRemaining = numCourses;
        for (int i = 0; i < numCourses; i++){
            if (!indegree.containsKey(i)){
                queue.offer(i);
                coursesRemaining--;
            }
            neighbors.put(i, new HashSet<Integer>());
        }
        for (int i = 0; i < prerequisites.length; i++){
            neighbors.get(prerequisites[i][1]).add(prerequisites[i][0]);
        }

        while (!queue.isEmpty()){
            Integer curt = queue.poll();
            for(Integer nei : neighbors.get(curt)){
                indegree.put(nei, indegree.get(nei) - 1);
                if (indegree.get(nei) == 0){
                    queue.offer(nei);
                    coursesRemaining--;
                }
            }
        }
        // System.out.print(coursesRemaining);
        return coursesRemaining == 0;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,041評(píng)論 0 23
  • 燈黑了那一整夜,睡不著,躺在閣樓上。樓下是爺爺剛安息的靈位,父親和姑姑正在為爺爺徹夜守靈。已經(jīng)是午夜12時(shí)了,寂靜...
    陳仲夏閱讀 344評(píng)論 0 2
  • 也是暈了 爸媽房間的空調(diào)竟然壞了 由于我一直喊木有零食 媽咪給我買(mǎi)了一堆零食 感覺(jué)自己在家就是次了睡 睡了次
    角落蜷縮閱讀 154評(píng)論 0 0
  • 到了中年,那種奮發(fā)有為的精神狀態(tài)銳減,倒是想著上有老、下有小這種境況下,自己健康才能承受贍養(yǎng)和撫養(yǎng)責(zé)任的事...
    認(rèn)識(shí)就是緣閱讀 567評(píng)論 0 1
  • 工作忙,身體累,國(guó)企巨輪未熬一甲子。 味道美,價(jià)格廉,沙棉小吃回憶三代人。 臨江仙,沙棉小吃。 客似云來(lái)常聚往,曾...
    徐云喜閱讀 978評(píng)論 9 5

友情鏈接更多精彩內(nèi)容