- LeetCode 최소 하루에 하나는 풀자는 마인드
- 사용언어: JAVA
207. Course Schedule
풀이
- 방법: 선수강 관계를 directed graph로 구현. dfs 함수로 현재 수강해야하는 과목들을 저장해 cycle 추적
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
int[] state = new int[numCourses];
for(int i = 0; i < numCourses; i++){
graph.add(new ArrayList<>());
}
for(int[] pre: prerequisites){
graph.get(pre[0]).add(pre[1]);
}
for(int i = 0; i < numCourses; i++){
if(!dfs(i, state, graph)) return false;
}
return true;
}
private boolean dfs(int node, int[] state, List<List<Integer>> graph){
if (state[node] == 1) return false;
if (state[node] == 2) return true;
state[node] = 1;
for (int next : graph.get(node)) {
if (!dfs(next, state, graph)) return false;
}
state[node] = 2;
return true;
}
}