Course Schedule II

public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] re =new int[numCourses] ; 
        int can = 0;
        int[] cnt = new int[numCourses] ; // for each course, how many prerequisites
        LinkedList<Integer> st = new LinkedList<Integer>(); //   courses which need no prerequisites
        int m = prerequisites.length;
        for(int i=0; i<m; i++){
            cnt[prerequisites[i][0]]++;
        }
        for(int i=0; i< numCourses; i++){
            if(cnt[i]==0){
                re[can++]=i;
                st.push(i);   
            }
        }
        while(!st.isEmpty()){
            int cur = st.pop();
            for(int i=0;i<m;i++){
                if(prerequisites[i][1]==cur){
                    if(--cnt[prerequisites[i][0]]==0){
                        re[can++]=prerequisites[i][0];
                        st.push(prerequisites[i][0]);
                    }
                }
            }
        }
        return can== numCourses? re: new int[0];
    }
}

BFS

ref http://www.meetqun.com/thread-9208-1-1.html

posted @ 2015-05-26 05:17  世界到处都是小星星  阅读(168)  评论(0编辑  收藏  举报