LeetCode207、210 课程表(图 dfs 拓扑排序)

时间:2024-04-05 06:59:12

官方题解主要思想是使用dfs进行拓扑排序。

课程表

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        edges = collections.defaultdict(list) 
        visited = [0] * numCourses # 将列表初始化为numCourses个0
        # result = []
        valid = True

        for info in prerequisites:
            edges[info[1]].append(info[0]) # info[1]是哪些课程的依赖(先决条件)    
                
        def dfs(u: int):
            nonlocal valid
            visited[u] = 1
            for v in edges[u]:
                if visited[v] == 0:
                    dfs(v)
                    if not valid:
                        return
                elif visited[v] == 1:
                    valid = False
                    return
            visited[u] = 2
            # result.append(u)
        
        for i in range(numCourses):
            if valid and not visited[i]:
                dfs(i)
        
        return valid

课程表二

class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        edges = collections.defaultdict(list)
        visited = [0]*numCourses
        result = []
        valid =True

        for info in prerequisites:
            edges[info[1]].append(info[0])

        def dfs(u):
            nonlocal valid
            visited[u]=1
            for v in edges[u]:
                if visited[v]==0:
                    dfs(v)
                elif visited[v]==1:
                    valid=False
                    return 

            visited[u]=2
            result.append(u)

        for i in range(numCourses):
            if valid and not visited[i]:
                dfs(i)

        if valid==True:
            result.reverse()
            return result
        else:
            return []