Java Simple Solution with comments (5ms), beats 98.42%


  • 1
    L
    public class Solution {
        public boolean canFinish(int numCourses, int[][] prereq) {
            int[] visited = new int[numCourses];
            
            //courses that would have the dependency graph
            List<List<Integer>> courses = new ArrayList<List<Integer>>();
            
            for(int i=0;i<numCourses;i++){
                courses.add(new ArrayList<Integer>());
            }
            
            //add dependencies
            for(int i=0;i< prereq.length;i++){
                // for a course, add all the courses that are dependent on it
                courses.get(prereq[i][1]).add(prereq[i][0]);
            }
            
            for(int i=0;i<numCourses;i++){
                if(visited[i]==0){
                    if(!dfs(i,courses,visited)) return false;
                }
            }
            return true;
    
        }
        
        public boolean dfs(int i,List<List<Integer>> courses, int[]visited){
            visited[i] = 1;
            
            // these are all the courses which are eligible
            //when we take their prerequisite, which is course i
            List<Integer> eligibleCourses = courses.get(i);
            
            for(int j=0;j<eligibleCourses.size();j++){
                int eligibleCourse = eligibleCourses.get(j);
                //it is already visited, during previous dfs call, so its a cycle 
                if(visited[eligibleCourse] == 1) return false;
                if(visited[eligibleCourse] == 2) continue;
                   if(!dfs(eligibleCourse,courses,visited)){
                        return false;
                    } 
            }
            
            //it is totally complete and no cycle found in its depth first traversal
            visited[i] = 2;
            return true;
            
            
        }
    }
    

Log in to reply
 

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