207. 课程表 - 力扣(LeetCode)

大佬图示

可以正确执行

会形成Loop

代码

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 21:13 
# "Stay hungry,stay foolish."

class Solution(object):
    def canFinish(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: bool
        """
        preMap = [[] for _ in range(numCourses)]

        for crs, pre in prerequisites:
            preMap[crs].append(pre)

        # preMap = [
        #     [],      # 课程 0 没有先修课
        #     [0],     # 课程 1 需要先修 0
        #     [0],     # 课程 2 需要先修 0
        #     [1]      # 课程 3 需要先修 1
        # ]

        # visitSet = all courses along the curr DFS path
        visitSet = set()

        def dfs(crs):
            if crs in visitSet:
                return False
            if preMap[crs] == []:
                return True
            visitSet.add(crs)

            for pre in preMap[crs]:
                if not dfs(pre):
                    return False
            visitSet.remove(crs)
            preMap[crs] = []
            return True

        for crs in range(numCourses):
            if not dfs(crs):
                return False
        return True

结果

解题步骤:www.bilibili.com

相关推荐
小小杨树几秒前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE21216 小时前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE21216 小时前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术21 小时前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦1 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050731 天前
(一)小红的数组操作
算法·编程语言
怕浪猫1 天前
Electron 系列文章封面图
算法·架构·前端框架
徐小夕1 天前
JitWord 3.0 正式发布,高精度Word异构解析+复杂组件兼容,打造web端协同Word编辑器
前端·vue.js·算法
通信小呆呆2 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人