题目
拓扑排序(bfs)
class Solution(object):
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
rudu = [0 for i in range(numCourses)]
libian = [[] for i in range(numCourses)]
from collections import deque
queue = deque()
for first, second in prerequisites:
rudu[first] += 1
libian[second].append(first)
for i in range(numCourses):
if rudu[i] == 0:
queue.append(i)
while queue:
pre = queue.pop()
numCourses -= 1
for cur in libian[pre]:
rudu[cur] -= 1
if rudu[cur] == 0:
queue.appendleft(cur)
return not numCourses
课程表2
class Solution(object):
def findOrder(self, numCourses, prerequisites):
rudu = [0 for i in range(numCourses)]
libian = [[] for i in range(numCourses)]
from collections import deque
queue = deque()
for first, second in prerequisites:
rudu[first] += 1
libian[second].append(first)
for i in range(numCourses):
if rudu[i] == 0:
queue.append(i)
res = []
while queue:
pre = queue.pop()
res.append(pre)
numCourses -= 1
for cur in libian[pre]:
rudu[cur] -= 1
if rudu[cur] == 0:
queue.appendleft(cur)
if numCourses != 0:
return []
return res