高频算法题 —— 检测循环依赖(拓扑排序)

检测循环依赖介绍


检测循环依赖本质就是使用 拓扑排序 判断图中是否有环、给出拓扑排序的结果

详情请移步 检测循环依赖

LeetCode 207. 课程表


题目链接

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        # 初始化邻接表
        adjacency=[[] for _ in range(numCourses)]
        # 初始化每个点的入度
        indegrees=[0 for _ in range(numCourses)]
        # 遍历prerequisites为邻接表、每个点的入度赋值
        for cur,pre in prerequisites:
            adjacency[pre].append(cur)
            indegrees[cur]+=1
        # 将所有入度为0的节点入队
        from collections import deque
        queue=deque()
        for i in range(numCourses):
            if indegrees[i]==0:
                queue.append(i)
        # 使用拓扑排序(依次将队列中入度为0的节点出队)
        while queue:
            pre=queue.popleft()
            numCourses-=1
            # 将pre后面的节点cur的入度通通-1
            for cur in adjacency[pre]:
                indegrees[cur]-=1
                if indegrees[cur]==0:
                    queue.append(cur)
        return not numCourses # 有环numCourses非0返回False
                              # 无环numCourses为0返回True

LeetCode 210. 课程表 II

题目链接

class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        adjacency=[[] for _ in range(numCourses)]
        indegrees=[0 for _ in range(numCourses)]
        for cur,pre in prerequisites:
            adjacency[pre].append(cur)
            indegrees[cur]+=1
        from collections import deque
        queue=deque()
        for i in range(numCourses):
            if indegrees[i]==0:
                queue.append(i)
        res=[]
        while queue:
            pre=queue.popleft()
            res.append(pre)
            for cur in adjacency[pre]:
                indegrees[cur]-=1
                if indegrees[cur]==0:
                    queue.append(cur)
        if len(res)==numCourses:
            return res
        else:
            return []

你可能感兴趣的:(#,LeetCode,算法,leetcode)