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

  • 1
    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
            for(int i=0;i<numCourses;i++){
                    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;
                        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.