1.  题目

【LeetCode】207.课程表_算法

2. 分析

这题的官方题解给出了一个深搜版本的代码,值得学习。

3. 代码

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        # 记录每门课程的入度
        in_degree = [0] * numCourses
        c2c = defaultdict(list)
        for i in range(len(prerequisites)):
            a,b = prerequisites[i]
            in_degree[a] += 1
            c2c[b].append(a)

        cnt = 0 # 已经上过的课
        while(True):
            # 找出一门课程,它的入度为0,可以先学习,并释放依赖
            cur_learn = 0
            while(cur_learn < numCourses):
                if in_degree[cur_learn] == 0:
                    cnt+=1
                    in_degree[cur_learn] = -1 # 置标签
                    break
                cur_learn += 1
            if cur_learn == numCourses:
                break
            for i in c2c[cur_learn]:
                if in_degree[i] > 0:
                    in_degree[i] -= 1
        if cnt == numCourses:
            return True
        return False
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.