课程安排汇总

lc 210 

把课程关系转成有向图,对图进行深度优先遍历,checked标记已经访问过的节点,order保存访问顺序

也用到了回溯算法:

课程安排汇总_第1张图片

class Solution:
    # checked 数组保存已经保存过的节点, visited记录当前访问过的节点, checked记录访问过的不会产生环的节点
    # order保存访问顺序,v当前访问节点
    def has_cycle(self,graph,visited,checked,v,path):
        if visited[v]: # 当前过程已经访问过
            return True
        visited[v] = True 
        for i in graph[v]:
            if not checked[i] and self.has_cycle(graph,visited,checked,i,path):
                return True
        checked[v] = True
        visited[v] = False
        path.append(v)
        return False

    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        if not prerequisites or len(prerequisites) == 0 or numCourses <=1:
            retur n [i for i in range(numCourses)]
        graph = []
        visited = []
        checked = []
        path = []

        for i in range(numCourses):
            graph.append([])
            checked.append(False)
            visited.append(False)
        
        for item in prerequisites:
            graph[item[1]].append(item[0])

        for i in range(numCourses):
            if not checked[i] and self.has_cycle(graph,visited,checked,i,path):
                return []
        path.reverse()
        return path

 

lc 207 

class Solution:
    def has_cycle(self,graph,visited,checked,v):
        if visited[v]:
            return True
        visited[v] = True
        for i in graph[v]:
            if not checked[i] and self.has_cycle(graph,visited,checked,i):
                return True
        checked[v] = True
        visited[v] = False
        return False 

    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        if not prerequisites or len(prerequisites) == 0 or numCourses<=1:
            return True
        graph = []
        visited = []
        checked = []

        for i in range(numCourses):
            graph.append([])
            checked.append(False)
            visited.append(False)
        
        for item in prerequisites:
            graph[item[1]].append(item[0])

        for i in range(numCourses):
            if not checked[i] and self.has_cycle(graph,visited,checked,i):
                return False
        return True

 

 

 

 

 

 

 

 

你可能感兴趣的:(LeetCode)