My Easy Understanding Java Solution


  • 0
    B
    
    public class Solution {
     private boolean [] isVisited = null;
    	private boolean [] canBeFinished = null;
    	private List<Integer> [] coursePrerequisties = null;
    
    	public boolean canFinish(int numCourses, int[][] prerequisites) {
    		initializeCourseSchedule(numCourses, prerequisites);
    		for(int i=0;i<numCourses;i++){
    			if (canBeFinished[i]) {
    				continue;
    			}
    			if (!finishCourse(i)) {
    				return false; 
    			}
    		}
            return true;
        }
    	private void initializeCourseSchedule(int numCourses,int [][]prerequisites){
    		isVisited = new boolean[numCourses];
    		canBeFinished = new boolean[numCourses];
    		coursePrerequisties = new List[numCourses];
    		for(int i=0;i<numCourses;i++){
    			coursePrerequisties[i] = new ArrayList<>();
    		}
    		for(int i=0;i<prerequisites.length;i++){
    			final int courseCode = prerequisites[i][0];
    			final int preCouseCode = prerequisites[i][1];
    			coursePrerequisties[courseCode].add(preCouseCode);
    		}
    	}
    	private boolean finishCourse(int courseCode){
    		if (isVisited[courseCode]) {
    			return false;
    		}
    		for(Integer nextCourseCode:coursePrerequisties[courseCode]){
    			isVisited [courseCode] = true;
    			if (!finishCourse(nextCourseCode)) {
    				return false;
    			}
    			isVisited [courseCode] = false;
    		}
    		canBeFinished[courseCode] = true;
    	
    		return true;
    	}
    }

Log in to reply
 

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