Published:
Updated:

  • Reference
  • graph
    • λ°±μ€€: List
    • LeetCode: defaultdict(list)


SolutionPermalink

import collections
from typing import List


class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        graph = collections.defaultdict(list)

        for x, y in prerequisites:
            graph[x].append(y)

        traced, visited = set(), set()

        def dfs(index) -> bool:
            # μˆœν™˜ ꡬ쑰일 λ•Œ
            if index in traced:
                return False

            # 이미 λ°©λ¬Έν–ˆλ˜ λ…Έλ“œμΌ λ•Œ
            if index in visited:
                return True

            traced.add(index)

            for y in graph[index]:
                # μˆœν™˜ ꡬ쑰일 λ•Œ
                if not dfs(y):
                    return False

            # 탐색 μ’…λ£Œ ν›„ -> μˆœν™˜, λ°©λ¬Έ λ…Έλ“œ 각각 μ‚­μ œ, μΆ”κ°€
            traced.remove(index)
            visited.add(index)

            return True

        for x in list(graph):
            if not dfs(x):
                return False

        return True

Leave a comment