Small changes from 207 Course Schedule.


  • 0
    P

    Small changes from 207. Course Schedule.

    public class Solution {
        public int[] findOrder(int numCourses, int[][] prerequisites) {
            int[][] graph = new int[numCourses][numCourses];
            int[] indegree = new int[numCourses];
            
            for(int i = 0; i < prerequisites.length; i++){
                int basic = prerequisites[i][0];
                int pre = prerequisites[i][1];
                if(graph[pre][basic] == 0)
                   indegree[basic]++;
                graph[pre][basic] = 1;
            }
            
            int count = 0;
            Queue<Integer> queue = new LinkedList<Integer>();
            ArrayList<Integer> result = new ArrayList<Integer>();
            for(int i = 0; i < indegree.length; i++){
                if(indegree[i] == 0) {
                    queue.offer(i);
                    result.add(i);
                }
            }
            
            while(!queue.isEmpty()){
                int pre = queue.poll();
                count++;
                for(int i = 0; i < numCourses; i++){
                    if(graph[pre][i] == 1){
                        if(--indegree[i] == 0){
                            queue.offer(i);
                            result.add(i);
                        }
                    }
                }
            }
            
            if(count == numCourses){
                int[] schedule = new int[numCourses];
                for(int i = 0; i < result.size(); i++){
                    schedule[i] = result.get(i);
                }
                return schedule;
            }
            else 
                return new int[0];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.