随笔- 509  文章- 0  评论- 151  阅读- 22万 

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
复制代码

 

 posted on   zhuli19901106  阅读(378)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
历史上的今天:
2014-05-08 Careercup - Google面试题 - 5680330589601792
2014-05-08 Careercup - Google面试题 - 5424071030341632
2014-05-08 Careercup - Google面试题 - 5377673471721472
2014-05-08 Careercup - Google面试题 - 6331648220069888
2014-05-08 Careercup - Google面试题 - 5692127791022080
2014-05-08 Careercup - Google面试题 - 4847954317803520
2014-05-08 Careercup - Google面试题 - 5765091433644032
点击右上角即可分享
微信分享提示