当前位置:网站首页>leetcode210. 课程表 II 207. 课程表 拓扑排序 dfs bfs
leetcode210. 课程表 II 207. 课程表 拓扑排序 dfs bfs
2022-06-23 06:30:00 【会写代码的孙悟空】
拓扑排序
对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边<u,v>∈E(G),则u在线性序列中出现在v之前。通常,这样的线性序列称为满足拓扑次序(Topological Order)的序列,简称拓扑序列。简单的说,由某个集合上的一个偏序得到该集合上的一个全序,这个操作称之为拓扑排序。
题目描述
- 课程表 II
现在你总共有 numCourses 门课需要选,记为 0 到 numCourses - 1。给你一个数组 prerequisites ,其中 prerequisites[i] = [ai, bi] ,表示在选修课程 ai 前 必须 先选修 bi 。
例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示:[0,1] 。
返回你为了学完所有课程所安排的学习顺序。可能会有多个正确的顺序,你只要返回 任意一种 就可以了。如果不可能完成所有课程,返回 一个空数组 。
示例 1:
输入:numCourses = 2, prerequisites = [[1,0]]
输出:[0,1]
解释:总共有 2 门课程。要学习课程 1,你需要先完成课程 0。因此,正确的课程顺序为 [0,1] 。
示例 2:
输入:numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
输出:[0,2,1,3]
解释:总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。
因此,一个正确的课程顺序是 [0,1,2,3] 。另一个正确的排序是 [0,2,1,3] 。
示例 3:
输入:numCourses = 1, prerequisites = []
输出:[0]
提示:
1 <= numCourses <= 2000
0 <= prerequisites.length <= numCourses * (numCourses - 1)
prerequisites[i].length == 2
0 <= ai, bi < numCourses
ai != bi
所有[ai, bi] 互不相同
解法思路
题目给了有向图,我们得到拓扑排序,就是最终的解
dfs
#dfs
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
ans=[]
valid=True
visited=[0]*numCourses
edges=collections.defaultdict(list)
for pre in prerequisites:
edges[pre[1]].append(pre[0])
def dfs(course):
nonlocal valid
visited[course]=1
for next_course in edges[course]:
if not valid:
return
if visited[next_course]==0:
dfs(next_course)
elif visited[next_course]==1:
valid=False
return
visited[course]=2
ans.append(course)
for course in range(numCourses):
if visited[course]==0:
dfs(course)
if not valid:
break
if valid:
return ans[::-1]
else:
return []
bfs
#bfs
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
from collections import deque
q=deque()
in_counts=[0]*numCourses
edges=collections.defaultdict(list)
ans=[]
for pre in prerequisites:
edges[pre[1]].append(pre[0])
in_counts[pre[0]]+=1
for i,in_count in enumerate(in_counts):
if in_count==0:
q.appendleft(i)
while q:
course=q.pop()
ans.append(course)
for next_course in edges[course]:
#print(in_counts)
in_counts[next_course]-=1
if in_counts[next_course]==0:
q.appendleft(next_course)
if len(ans)==numCourses:
return ans
else:
return []
边栏推荐
- JUnit unit test reports an error org junit. runners. model. InvalidTestClassError: Invalid test class ‘xxx‘ . No runnable meth
- 303. region and retrieval - array immutable
- pspnet完整代码实现
- Arthas-thread命令定位线程死锁
- TP6+Redis+think-queue+Supervisor实现进程常驻消息队列/job任务
- 【AI实战】XGBRegressor模型加速训练,使用GPU秒级训练XGBRegressor
- PSP code implementation
- 【AI实战】xgb.XGBRegressor之多回归MultiOutputRegressor调参2(GPU训练模型)
- 306. Addenda
- Pagoda forgot password
猜你喜欢

Endnote20 tutorial sharing (unfinished
![[system] right click the desktop icon. After turning around, the Explorer will crash and the desktop will be refreshed](/img/aa/0189beb065fa0d4b625390793cb79b.png)
[system] right click the desktop icon. After turning around, the Explorer will crash and the desktop will be refreshed

Advanced drawing skills of Excel lecture 100 (VIII) -excel drawing WiFi diagram

Mysql(十一) — MySQL面试题整理

别找了诸位 【十二款超级好用的谷歌插件都在这】(确定不来看看?)

406 double pointer (27. remove elements, 977. square of ordered array, 15. sum of three numbers, 18. sum of four numbers)

MySQL(八) — 执行计划(Explain)详解

Vs2013 ffmpeg environment configuration and common error handling

Traversal of binary tree and related knowledge

Interpreting the spirit of unity and cooperation in maker Education
随机推荐
Add IPAD control function into shairplay
深度学习系列46:人脸图像超分GFP-GAN
GINet
406 double pointer (27. remove elements, 977. square of ordered array, 15. sum of three numbers, 18. sum of four numbers)
Use of Lombok
数据库原理实验测试题,关于图书分类表
About professional attitude
别找了诸位 【十二款超级好用的谷歌插件都在这】(确定不来看看?)
Verilog syntax explanation
Analyzing the creation principle in maker Education
Mysql数据库的几个特点
C DPI adaptation problem
Page embedded iframe click browser back problem
MySQL总结
SSM整合
About SQL: is there a way to fill in the null value in the field without adding fields on the basis of the original fields
TP6+Redis+think-queue+Supervisor实现进程常驻消息队列/job任务
MySQL(二) — MySQL数据类型
Advanced drawing skills of Excel lecture 100 (VIII) -excel drawing WiFi diagram
295. median data flow