leetcode-207-课程表

Posted oldby

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-207-课程表相关的知识,希望对你有一定的参考价值。

题目描述:

技术图片

 

 技术图片

 

 方法一:dfs

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        def dfs(i, adjacency, flags):
            if flags[i] == -1: return True
            if flags[i] == 1: return False
            flags[i] = 1
            for j in adjacency[i]:
                if not dfs(j, adjacency, flags): return False
            flags[i] = -1
            return True
        
        adjacency = [[] for _ in range(numCourses)]
        flags = [0 for _ in range(numCourses)]
        for cur, pre in prerequisites:
            adjacency[pre].append(cur)
        for i in range(numCourses):
            if not dfs(i, adjacency, flags): return False
        return True

方法二:拓扑排序,bfs

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:    
        adjacency = [[] for _ in range(numCourses)]
        indegrees = [0 for _ in range(numCourses)]
        for cur, pre in prerequisites:
            adjacency[pre].append(cur)
            indegrees[cur] += 1
        queue = []
        for i in range(numCourses):
            if not indegrees[i]:
                queue.append(i)
        while queue:
            pre = queue.pop(0)
            numCourses -= 1
            for cur in adjacency[pre]:
                indegrees[cur] -= 1
                if indegrees[cur] == 0:
                    queue.append(cur)
        return numCourses==0
            

 

以上是关于leetcode-207-课程表的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 207. 课程表

LeetCode207 课程表

LeetCode - #207 课程表(Top 100)

[LeetCode] 207. 课程表(拓扑排序,BFS)

LeetCode207.课程表 | BFS DFS 邻接表 邻接矩阵

LeetCode207.课程表 | BFS DFS 邻接表 邻接矩阵