Lintcode 616. Course Schedule II

同样是拓扑排序,需要注意的是防治出现闭环的情况。当出现闭环,返回空。
python 代码:

class Solution:
    """
    @param: numCourses: a total of n courses
    @param: prerequisites: a list of prerequisite pairs
    @return: the course order
    """
    def findOrder(self, numCourses, prerequisites):
        # write your code here
        from collections import deque
        edge = [[] for i in range(numCourses)]
        indegree = [0] * numCourses
        for i, j in prerequisites:
            edge[j].append(i)
            indegree[i] += 1
        res = []
        queue = deque()
        cnt = 0
        for i in range(numCourses):
            if indegree[i] == 0:
                queue.append(i)
        while queue:
            course = queue.popleft()
            res.append(course)
            cnt += 1
            for neighbor in edge[course]:
                indegree[neighbor] -= 1
                if indegree[neighbor] == 0:
                    queue.append(neighbor)
        if cnt != numCourses:
            return []
        return res

你可能感兴趣的:(Lintcode 616. Course Schedule II)