码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Course Schedule

时间:2015-05-08 06:54:18      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Course Schedule

2015.5.8 01:26

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Solution:

  This problem is about topological sort. Watch out for multigraph.

Accepted code:

# My code looks ugly enough...
class Solution:
    # @param {integer} numCourses
    # @param {integer[][]} prerequisites
    # @return {boolean}
    def canFinish(self, numCourses, prerequisites):
        e = prerequisites
        n = numCourses
        
        g = [set() for i in xrange(n)]
        ind = [0 for i in xrange(n)]
        ec = len(e)
        for i in xrange(ec):
            g[e[i][0]].add(e[i][1])
        ec = 0
        for i in xrange(n):
            for j in g[i]:
                ind[j] += 1
            ec += len(g[i])
        b = [False for i in xrange(n)]
        while True:
            i = 0
            while i < n:
                if ind[i] == 0 and not b[i]:
                    break
                i += 1
            if i == n:
                break
            for j in g[i]:
                ind[j] -= 1
            g[i] = set()
            b[i] = True
        i = 0
        while i < n:
            if not b[i]:
                return False
            i += 1
        return True

 

LeetCode - Course Schedule

标签:

原文地址:http://www.cnblogs.com/zhuli19901106/p/4486604.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!