course schedule 2 bfs indegree

class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
      
      List<Integer> result = new ArrayList<>();
      Queue<Integer> queue = new LinkedList<>();
      List<List<Integer>> list = new ArrayList<>();
      int[] indegree = new int[numCourses];
      
      for(int i = 0; i < prerequisites.length; i++){
        int course = prerequisites[i][0];
        indegree[course]++;
      }
      
      for(int i = 0; i < numCourses; i++){
        list.add(new ArrayList<>());
      }
      
      for(int i = 0; i < prerequisites.length; i++){
        list.get(prerequisites[i][1]).add(prerequisites[i][0]);
      }
      
      for(int i = 0; i < numCourses; i++){
        if(indegree[i] == 0){
          queue.offer(i);
        
        }
      }
      
      while(!queue.isEmpty()){
        int cur = queue.poll();
        result.add(cur);
        
        for(int nei: list.get(cur)){
          indegree[nei]--;
          if(indegree[nei] == 0){
            queue.offer(nei);
          }
        }
      }
      if(result.size() == numCourses){
        int[] array = new int[numCourses];
        for(int i = 0; i < numCourses; i++){
          array[i] = result.get(i);
        }
        return array;
      }
      return new int[]{};
    }
}

bfs indegree 

 

 

Pretty much the same as the course schedule 1 

The only diff is to return the order of the classes, which we can use a list as a container 

Every time we see poll a node from the queue, we can add it to the list, since we know the node added to the queue has indegree 0. 

 

 

Input : 2, [[1,0]] 

 

 

At then end, when we need to return the result , the order 

Since we are not guaranteed that  we can finish all the classes , so we need to check If the list size is same as the total number of classes given in the input. 

 

If its the same, then we know we can finish all the classes 

And convert the list into int[] array, and return 

 

if it’s not the same, we can return int[] array which has nothing in it.  return new int[]{};

posted on 2018-09-08 10:50  猪猪&#128055;  阅读(113)  评论(0)    收藏  举报

导航