We can use bfs to solve this problem;

By traverse the prerequisites array, we can generate two graph representations. One is an array of list of out nodes of a certain node. The other is an array of list of in nodes of a certain node. 

We look into each course(node), if its out nodes list is empty, that means the node is an isolate node or an sink node(the end node of a connected component of the graph). We add those course node into the from the end part of result array(the order can be random). If it has in nodes find all of them in the list of in nodes list of current node and then remove current node in the out node list of each in node we found above. Then we go to the first step to findout new nodes which has no out nodes.

public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        
        int[] courseOrder = new int[numCourses];
        List<Integer>[] graph_in = (List<Integer>[]) new List[numCourses];
        List<Integer>[] graph_out = (List<Integer>[]) new List[numCourses];
        for(int i = 0; i < prerequisites.length; i++){
            int inNode = prerequisites[i][1];
            int outNode = prerequisites[i][0];
            if(graph_in[inNode] == null) graph_in[inNode] = new ArrayList<>();
            if(graph_out[outNode] == null) graph_out[outNode] = new ArrayList<>();
            graph_in[inNode].add(outNode);
            graph_out[outNode].add(inNode);
        }
        //boolean[] isMark = new boolean[numCourses];
        boolean[] added = new boolean[numCourses];
        //boolean[] inCircle = new boolean[numCourses];
        int j = numCourses-1;
        while(j >= 0){
            int temp = j;
            for(int i = 0; i < numCourses; i++){
                int outNode = i;
                if(!added[i] && (graph_in[i] == null || graph_in[i].isEmpty())){
                    courseOrder[j] = i;
                    added[i] = true;
                    j--;
                    List<Integer> list = graph_out[i];
                    if(list == null) continue;
                    for(int k = 0; k < list.size(); k++){
                        graph_in[list.get(k)].remove(Integer.valueOf(i));
                    }
                }
            }
            if(j == temp) return new int[0];
        }
        return courseOrder;
        
    }
}

  

posted on 2016-02-23 07:31  爱推理的骑士  阅读(164)  评论(0编辑  收藏  举报