Untitled

 avatar
unknown
python
9 months ago
949 B
19
Indexable
class Solution:
    def minimumSemesters(self, n: int, relations: List[List[int]]) -> int:
        nextCourses = defaultdict(list)
        dependencies_count = [0] * (n + 1)

        for relation in relations:
            (prerequisite, target) = relation
            dependencies_count[target] += 1
            nextCourses[prerequisite].append(target)
        processing = deque([i for i in range(1, n + 1) if dependencies_count[i] == 0])
        semester = 0
        completed = 0
        while processing:
            semester += 1
            for _ in range(len(processing)):
                cource = processing.popleft()
                completed += 1
                targets = nextCourses[cource]
                for target in targets:
                    dependencies_count[target] -= 1
                    if dependencies_count[target] == 0:
                        processing.append(target)
        return semester if completed == n else -1
Editor is loading...
Leave a Comment