Published:
Updated:

  • Reference
  • graph
    • ๋ฐฑ์ค€: List
    • LeetCode: defaultdict(list)


Solution

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