Description:
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Solution:
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
ArrayList[] graph = new ArrayList[numCourses];
for(int i = 0; i < numCourses; ++i)
graph[i] = new ArrayList();
boolean[] dp = new boolean[numCourses];
boolean visited[] = new boolean[numCourses];
for(int i = 0; i < prerequisites.length; ++i)
graph[prerequisites[i][1]].add(prerequisites[i][0]);
for(int i = 0; i < numCourses; ++i)
if(!dfs(graph, i, visited, dp))
return false;
return true;
}
//dfs to check whether the graph has cycle
public boolean dfs(ArrayList[] graph, int course, boolean[] visited, boolean[] dp) {
if(visited[course]) {
dp[course] = false;
return false;
}
else
visited[course] = true;
for(int i = 0; i < graph[course].size(); ++i)
if(!dfs(graph, (int) graph[course].get(i), visited, dp)) {
dp[course] = false;
return false;
}
visited[course] = false;
dp[course] = true;
return true;
}
}