210. Course Schedule II

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]

2, [[1,0]] 
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].
Topo-sort 在leetcode裏只有幾個題目,並且邏輯徹底同樣。只要清楚的記得幾大步驟就能夠解題啦。
1. 創建入度indegree.
2. 組成cousePairs,把原來輸入的無規律edges,轉換成 out -> List<Integer> 另外一種表示圖的方法。
3. 找到indegree爲零的點,放到Queue裏,也就是咱們topo-sort 圖的入口。
4. 從Q裏彈出點,寫到結果裏。對於它的neighbors, 也就是out指向的in。這裏題目意思是preCourses, 由於咱們已經上過這門課,
因此須要上的課也就少了一門。若是這些neighbors的入度也變成0,也就變成了新的入口,加入到Q裏,重複4.
5. 返回結果。
public class Solution {
    public int[] findOrder(int num, int[][] pres) {
        int[] res = new int[num];
        
        int[] indegree = new int[num];
        List<Integer>[] pairs = new List[num];
        
        for(int[] pre : pres){
            // pre[0] in, pre[1] out
            int in = pre[0], out = pre[1];
            indegree[in]++;
            if(pairs[out] == null)
                pairs[out] = new ArrayList<Integer>();
            pairs[out].add(in);
        }
        
        Queue<Integer> q = new LinkedList<>();
        
        for(int i = 0; i < num; i++){
            if(indegree[i] == 0) q.offer(i);
        }
        
        int t = 0;
        while(!q.isEmpty()){
            int out = q.poll();
            res[t++] = out;
            if(pairs[out] == null) continue;      // 這裏題目有可能沒有預修課,能夠直接上任意課程。
            for(int in : pairs[out]){
                indegree[in]--;
                if(indegree[in] == 0) q.offer(in);
            }
        }
        
        return t == num ? res : new int[0];
    }
}
相關文章
相關標籤/搜索