207. Course Schedule

2026. 3. 9. 20:33Algorithm/Leetcode, Lintcode, HackerRank, etc.

    목차
반응형

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:

        g = collections.defaultdict(list)

        for u, v in prerequisites:
            g[u] += v,

        topology = collections.defaultdict(int)
        for u, adjs in g.items():
            for v in adjs:
                topology[v] += 1

        q = collections.deque()
        visited = set()

        for i in range(numCourses):
            if topology[i] == 0:
                q += i,
                visited.add(i)

        while q:
            u = q.popleft()

            for v in g[u]:
                if v in visited:
                    continue

                topology[v] -= 1
                if topology[v] == 0:
                    q += v,
                    visited.add(v)

        return len(visited) == numCourses
반응형

'Algorithm > Leetcode, Lintcode, HackerRank, etc.' 카테고리의 다른 글

Graph Valid Tree  (0) 2026.03.10
Palindrome Permutation  (0) 2026.03.10
Find the smallest balanced index  (0) 2026.03.08
Minumum Capacity Box  (0) 2026.03.08
3341. Find Minimum Time to Reach Last Room I  (0) 2026.03.08