210 Course Schedule II

拓扑排序, 输出一种可能的排序结果,207 Course Schedule 稍微变化一点即可得到正确答案

from collections import defaultdict
class Solution:
    # @param {integer} numCourses
    # @param {integer[][]} prerequisites
    # @return {boolean}
    def findOrder(self, numCourses, prerequisites):
        inNum = [0 for i in range(numCourses)]
        dic = defaultdict(list)
        for [v, u] in prerequisites:
            dic[u].append(v)
            inNum[v] += 1
        totalNum = 0
        ans = []
        while 0 in inNum:
            u = inNum.index(0)
            ans.append(u)
            if u in dic:
                for v in dic[u]:
                    inNum[v] -= 1
            inNum[u] = None
            totalNum += 1
        if totalNum == numCourses:
            return ans
        return []

 

posted @ 2015-07-07 13:28  dapanshe  阅读(109)  评论(0编辑  收藏  举报