Course Schedule
這題的本質就是,給你一個代表 graph 的 adjacency array,判斷 graph 是否有環。其實和 Graph Valid Tree 非常像。
DFS 找環性能優異,DFS找環相當於在DFS的基礎上(1)需要傳一個visited數組,每次訪問某個點的時候判斷該點的visit數值,如果爲0表示沒有被訪問過,1表示有環,2表示訪問完成。再次訪問1肯定有環。
public boolean canFinish(int numCourses, int[][] prerequisites) {
ArrayList[] graph = new ArrayList[numCourses];
int[] visited = new int[numCourses];
for(int i = 0; i < numCourses; i++){
graph[i] = new ArrayList<Integer>();
}
for(int[] num : prerequisites){
int parent = num[1];
int child = num[0];
graph[parent].add(child);
}
for(int i = 0; i < numCourses; i++){
if(visited[i] == 0 && hasCycle(i, visited, graph)) return false;
}
return true;
}
private boolean hasCycle(int cur, int[] visited, ArrayList[] graph){
visited[cur] = 1;
boolean hasCycle = false;
for(int i = 0; i < graph[cur].size(); i++){
int next = (int) graph[cur].get(i);
if(visited[next] == 1) return true;
else if(visited[next] == 0){
hasCycle = hasCycle || hasCycle(next, visited, graph);
}
}
visited[cur] = 2;
return hasCycle;
}
}