zoukankan      html  css  js  c++  java
  • LeetCode

    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][1]].add(e[i][0])
            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
  • 相关阅读:
    条件注释判断浏览器版本<!--[if lt IE 9]>
    动态加载js、css 代码
    C趣味题目
    shell脚本
    Logiscope学习网址
    将double型小数点后面多余的零去掉
    qt和makefile学习网址
    微软推出的工作流引擎
    java例子
    js 定义hash类
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/4486604.html
Copyright © 2011-2022 走看看