Skip to content

LeetCode #210:课程表 II

https://leetcode.cn/problems/course-schedule-ii/description/

题目分析

标准的 DFS+染色算法。

题解

python
class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        g = defaultdict(list)
        for i, j in prerequisites:
            g[i].append(j)

        status = [0] * numCourses
        seq = []

        def dfs(i):  # 染色DFS
            # 维护一个染色状态, enum 没访问过, 成环, 已完全访问
            if status[i] == 2:  # 已完全访问
                return True
            if status[i] == 1:  # 成环
                return False
            # 还没访问过
            status[i] = 1 # 标记为已访问(下次再访问就成环)
            for nbr in g[i]:
                if not dfs(nbr):
                    return False  # 成环了
            status[i] = 2  # 把访问过的节点标记为已完全访问
            seq.append(i)
            return True

        for i in range(numCourses):
            if not dfs(i):
                return []

        return seq

页面历史

Powered by VitePress and Elysium UI.
This site uses Microsoft Clarity to see how you use our website. By using our site, you agree that we and Microsoft can collect and use this data.