码迷,mamicode.com
首页 > 其他好文 > 详细

Course Schedule II; BFS; DFS;

时间:2016-02-23 08:24:58      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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;
        
    }
}

  

Course Schedule II; BFS; DFS;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5208686.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!