Course Schedule II; BFS; DFS;

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

  

转载于:https://www.cnblogs.com/5683yue/p/5208686.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值