1 minute read

207. Course Schedule

문제 링크

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

문제 설명

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.

Return true if you can finish all courses. Otherwise, return false.

제한 사항

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • All the pairs prerequisites[i] are unique.

입출력 예 #1

  1. Input : numCourses = 2, prerequisites = [[1,0]]
  2. Output : true
  3. Explanation : There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

입출력 예 #2

  1. Input : numCourses = 2, prerequisites = [[1,0],[0,1]]
  2. Output : false
  3. Explanation : There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

문제 풀이

dfs 기법을 이용하여 순환 구조인 코스인지 판별하고, 이미 방문했던 노드는 skip 함으로써 속도도 높여 풀이한다.

class Solution:
    def canFinish(self, numCourses: int, prerequisited: List[List[int]) -> bool:
        graph = collections.defaultdict(list)
        # 그래프 구성
        for x, y in prerequisites:
            graph[x].append(y)

        traced = set()
        visited = set()

        def dfs(i):
            # 순환 구조이면 False
            if i in traced:
                return False

            # 이미 방문했던 노드이면 False
            if i in visited:
                return True

            traced.add(i)
            for y in graph[i]:
                if not dfs(y):
                    return False

            # 탐색 종료 후 순환 노드 삭제
            traced.remove(i)
            # 탐색 종료 후 방문 노드 추가
            visited.add(i)

            return True

        # 순환 구조 판별
        for x in list(graph):
            if not dfs(x):
                return False

        return True

Comments