[M] 207. Course Schedule

YJ·2026년 11월 20일

leetcode

목록 보기
61/100

https://leetcode.com/problems/course-schedule

문제

선수과목 리스트 쫙 있을 때 수업 모두 수강하는게 가능한지.. (Cycle 이 존재하는지 확인하는 문제라고 한다.

답안

class Solution {
    
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            graph.add(new ArrayList<>());
        }

        int[] indegrees = new int[numCourses];
        for (int[] p : prerequisites) {
            int from = p[1];
            int to = p[0];
            graph.get(from).add(to);
            indegrees[to]++;
        }

        Queue<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < numCourses; i++) {
            if (indegrees[i] == 0) {
                queue.offer(i);
            }
        }

        int visitedCount = 0;
        while (!queue.isEmpty()) {
            int curr = queue.poll();
            visitedCount++;

            for (int next : graph.get(curr)) {
                indegrees[next]--;
                if (indegrees[next] == 0) {
                    queue.offer(next);
                }
            }
        }
        return visitedCount == numCourses;
    }
}

메모

Cycle이 있는지 확인하는 데는 두 가지 방법이 있다고 한다.
1) 위 풀이처럼 위상정렬을 사용해서 방문한 노드가 총 노드의 개수와 같은지 확인하는 방법.. List<List> 로 인접리스트를 만들고, int[] indegrees 로 각 과목의 진입차수를 관리하고, zero degree 인 것부터 모두 큐에 넣고 뺄 때 인접 노드들의 차수들도 하나씩 줄여주는 방법.
2) 아래 풀이처럼 DFS 에서 white(0),gray(1),black(2) 로 확인하는 방법.. 재귀호출 중에 gray 인 노드를 만나면 현재 경로에서 사이클이 발생한 것이다.

class Solution {

    private static final int UNVISITED = 0;
    private static final int VISITING = 1;
    private static final int VISITED = 2;
    
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        List<List<Integer>> graph = new ArrayList<>(numCourses);
        for (int i = 0; i < numCourses; i++) {
            graph.add(new ArrayList<>());
        }

        for (int[] p : prerequisites) {
            int from = p[1];
            int to = p[0];
            graph.get(from).add(to);
        }
        
        int[] state = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            if (state[i] == UNVISITED && hasCycle(graph, state, i)) {
                return false;
            }
        }
        return true;
    }

    private boolean hasCycle(List<List<Integer>> graph, int[] state, int node) {
        if (state[node] == VISITING) {
            return true;
        }
        if (state[node] == VISITED) {
            return false;
        }
        state[node] = VISITING;
        for (int next : graph.get(node)) {
            if (hasCycle(graph, state, next)) {
                return true;
            }
        }
        state[node] = VISITED;
        return false;
    }
}
profile
Hello

0개의 댓글