【LeetCode】Course Schedule 解題報告,leetcodeschedule

來源:互聯網
上載者:User

【LeetCode】Course Schedule 解題報告,leetcodeschedule

【題目】

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.

【解析】

典型的拓撲排序。原理也很簡單,在一個有向圖中,每次找到一個沒有前驅節點的節點(也就是入度為0的節點),然後把它指向其他節點的邊都去掉,重複這個過程(BFS),直到所有節點已被找到,或者沒有合格節點(如果圖中有環存在)。

回顧一的三種表示方式:邊標記法(即題目中表示方法),鄰接表法,鄰接矩陣。用鄰接表格儲存體圖比較方便尋找入度為0的節點。

【Java代碼】

public class Solution {    public boolean canFinish(int numCourses, int[][] prerequisites) {        // init the adjacency list        List<Set> posts = new ArrayList<Set>();        for (int i = 0; i < numCourses; i++) {            posts.add(new HashSet<Integer>());        }                // fill the adjacency list        for (int i = 0; i < prerequisites.length; i++) {            posts.get(prerequisites[i][1]).add(prerequisites[i][0]);        }                // count the pre-courses        int[] preNums = new int[numCourses];        for (int i = 0; i < numCourses; i++) {            Set set = posts.get(i);            Iterator<Integer> it = set.iterator();            while (it.hasNext()) {            preNums[it.next()]++;            }        }                // remove a non-pre course each time        for (int i = 0; i < numCourses; i++) {            // find a non-pre course            int j = 0;            for ( ; j < numCourses; j++) {                if (preNums[j] == 0) break;            }                        // if not find a non-pre course            if (j == numCourses) return false;                        preNums[j] = -1;                        // decrease courses that post the course            Set set = posts.get(j);            Iterator<Integer> it = set.iterator();            while (it.hasNext()) {            preNums[it.next()]--;            }        }                return true;    }}

注意,輸入可能有重複的邊,所以鄰接表用HashSet儲存。

下面一種代碼是不用HashSet的,對於重複的邊,它在鄰接表中村了兩份,同時計算入度時也算了兩次,所以代碼不會有問題。但個人感覺最好用HashSet,這樣符合圖的定義。

下面的代碼還是比較典型的BFS寫法,大家可以對比理解下:

public class Solution {    public boolean canFinish(int numCourses, int[][] prerequisites) {        List<List<Integer>> posts = new ArrayList<List<Integer>>();        for (int i = 0; i < numCourses; i++) {            posts.add(new ArrayList<Integer>());        }                int[] preNums = new int[numCourses];        for (int i = 0; i < prerequisites.length; i++) {            posts.get(prerequisites[i][1]).add(prerequisites[i][0]);            preNums[prerequisites[i][0]]++;        }                Queue<Integer> queue = new LinkedList<Integer>();        for (int i = 0; i < numCourses; i++) {            if (preNums[i] == 0){                queue.offer(i);            }        }                int count = numCourses;        while (!queue.isEmpty()) {            int cur = queue.poll();            for (int i : posts.get(cur)) {                if (--preNums[i] == 0) {                    queue.offer(i);                }            }            count--;        }                return count == 0;    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.