Very Simple Java


  • 0
    K
    public class Solution {
        public static int cur;
        public static boolean cycle;
        public int[] findOrder(int numCourses, int[][] prerequisites) {
            if(prerequisites.length==0){
                int[] a =new int[numCourses];
                for(int i=0;i<numCourses;i++){
                    a[i]=i;
                }
                return a;
            }
            cycle=false;
            int[] res = new int[numCourses];
            int[] exp = new int[numCourses];
            int[] cyc = new int[numCourses];
            cur = numCourses-1;
            for(int i=0;i<numCourses;i++){
                if(cycle){
                	break;
                }
                if(exp[i]==0){
                    cyc = new int[numCourses];
                    Dfs(i,prerequisites,res,exp,cyc);
                }
            }
            if(!cycle){
            return res;
            }
            return new int[0];
        }
        
        public void Dfs(int i,int[][] prerequisites,int[] res,int[] exp,int[] cyc){
            exp[i]=1;
            cyc[i]=1;
            for(int k=0;k<prerequisites.length;k++){
                if(prerequisites[k][1]==i){
                    if(cyc[prerequisites[k][0]]==1){
                       cycle=true;
                    }
                    if(exp[prerequisites[k][0]]==0){
                        Dfs(prerequisites[k][0],prerequisites,res,exp,cyc);
                    }
                }
            }
            res[cur]=i;
            cyc[i]=0;
            cur=cur-1;
        }
    }

Log in to reply
 

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