207 Course Schedule

使用 拓扑排序, 使用刚学的defaultdict 哈哈

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

 

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