leetcode 课程表 II python

在《leetcode 课程表 python》的基础上稍作修改

class Solution(object):
    def findOrder(self, numCourses, prerequisites):
        deleted=[]
        dict_graph={}
        for i in range(numCourses):
            dict_graph[i]={}
        for prereq in prerequisites:
            dict_graph[prereq[0]][prereq[1]]=1
        def del0indegree(dict_graph,deleted):
            tobedel=[]
            for node in dict_graph:
                if len(dict_graph[node])==0:
                    tobedel.append(node)
            deleted=deleted+tobedel
            for tobedel_i in tobedel:
                del dict_graph[tobedel_i]
            for node in dict_graph:
                for tobedel_i in tobedel:
                    if tobedel_i in dict_graph[node]:
                        del dict_graph[node][tobedel_i]
            return deleted
            
        def has0indegree(dict_graph):
            for node in dict_graph:
                if len(dict_graph[node].keys())==0:
                    return True
            return False
        while has0indegree(dict_graph):
            deleted=del0indegree(dict_graph,deleted)
        return deleted if len(dict_graph.keys())==0 else []

你可能感兴趣的:(leetcode 课程表 II python)