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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题: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